diff --git a/engine/src/flutter/lib/web_ui/lib/src/ui/annotations.dart b/engine/src/flutter/lib/web_ui/lib/src/ui/annotations.dart index 7dac0c5670..c2670d5282 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/ui/annotations.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/ui/annotations.dart @@ -9,36 +9,6 @@ part of ui; // TODO(dnfield): Update this if/when we default this to on in the tool, // see: https://github.com/flutter/flutter/issues/52759 -/// Annotation used by Flutter's Dart compiler to indicate that an -/// [Object.toString] override should not be replaced with a supercall. -/// -/// Since `dart:ui` and `package:flutter` override `toString` purely for -/// debugging purposes, the frontend compiler is instructed to replace all -/// `toString` bodies with `return super.toString()` during compilation. This -/// significantly reduces release code size, and would make it impossible to -/// implement a meaningful override of `toString` for release mode without -/// disabling the feature and losing the size savings. If a package uses this -/// feature and has some unavoidable need to keep the `toString` implementation -/// for a specific class, applying this annotation will direct the compiler -/// to leave the method body as-is. -/// -/// For example, in the following class the `toString` method will remain as -/// `return _buffer.toString();`, even if the `--delete-tostring-package-uri` -/// option would otherwise apply and replace it with `return super.toString()`. -/// -/// ```dart -/// class MyStringBuffer { -/// StringBuffer _buffer = StringBuffer(); -/// -/// // ... -/// -/// @keepToString -/// @override -/// String toString() { -/// return _buffer.toString(); -/// } -/// } -/// ``` const _KeepToString keepToString = _KeepToString(); class _KeepToString { diff --git a/engine/src/flutter/lib/web_ui/lib/src/ui/canvas.dart b/engine/src/flutter/lib/web_ui/lib/src/ui/canvas.dart index 59e2c8eda1..1699a1a287 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/ui/canvas.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/ui/canvas.dart @@ -5,70 +5,24 @@ // @dart = 2.10 part of ui; -/// Defines how a list of points is interpreted when drawing a set of points. -/// -/// Used by [Canvas.drawPoints]. enum PointMode { - /// Draw each point separately. - /// - /// If the [Paint.strokeCap] is [StrokeCap.round], then each point is drawn - /// as a circle with the diameter of the [Paint.strokeWidth], filled as - /// described by the [Paint] (ignoring [Paint.style]). - /// - /// Otherwise, each point is drawn as an axis-aligned square with sides of - /// length [Paint.strokeWidth], filled as described by the [Paint] (ignoring - /// [Paint.style]). points, - - /// Draw each sequence of two points as a line segment. - /// - /// If the number of points is odd, then the last point is ignored. - /// - /// The lines are stroked as described by the [Paint] (ignoring - /// [Paint.style]). lines, - - /// Draw the entire sequence of point as one line. - /// - /// The lines are stroked as described by the [Paint] (ignoring - /// [Paint.style]). polygon, } -/// Defines how a new clip region should be merged with the existing clip -/// region. -/// -/// Used by [Canvas.clipRect]. enum ClipOp { - /// Subtract the new region from the existing region. difference, - - /// Intersect the new region from the existing region. intersect, } enum VertexMode { - /// Draw each sequence of three points as the vertices of a triangle. triangles, - - /// Draw each sliding window of three points as the vertices of a triangle. triangleStrip, - - /// Draw the first point and each sliding window of two points as the vertices of a triangle. triangleFan, } -/// A set of vertex data used by [Canvas.drawVertices]. class Vertices { - /// Creates a set of vertex data for use with [Canvas.drawVertices]. - /// - /// The [mode] and [positions] parameters must not be null. - /// - /// If the [textureCoordinates] or [colors] parameters are provided, they must - /// be the same length as [positions]. - /// - /// If the [indices] parameter is provided, all values in the list must be - /// valid index values for [positions]. factory Vertices( VertexMode mode, List positions, { @@ -77,34 +31,21 @@ class Vertices { List? indices, }) { if (engine.experimentalUseSkia) { - return engine.CkVertices(mode, positions, - textureCoordinates: textureCoordinates, - colors: colors, - indices: indices); - } - return engine.SurfaceVertices(mode, positions, + return engine.CkVertices( + mode, + positions, + textureCoordinates: textureCoordinates, colors: colors, - indices: indices); + indices: indices, + ); + } + return engine.SurfaceVertices( + mode, + positions, + colors: colors, + indices: indices, + ); } - - /// Creates a set of vertex data for use with [Canvas.drawVertices], directly - /// using the encoding methods of [new Vertices]. - /// - /// The [mode] parameter must not be null. - /// - /// The [positions] list is interpreted as a list of repeated pairs of x,y - /// coordinates. It must not be null. - /// - /// The [textureCoordinates] list is interpreted as a list of repeated pairs - /// of x,y coordinates, and must be the same length of [positions] if it - /// is not null. - /// - /// The [colors] list is interpreted as a list of RGBA encoded colors, similar - /// to [Color.value]. It must be half length of [positions] if it is not - /// null. - /// - /// If the [indices] list is provided, all values in the list must be - /// valid index values for [positions]. factory Vertices.raw( VertexMode mode, Float32List positions, { @@ -113,25 +54,24 @@ class Vertices { Uint16List? indices, }) { if (engine.experimentalUseSkia) { - return engine.CkVertices.raw(mode, positions, - textureCoordinates: textureCoordinates, - colors: colors, - indices: indices); - } - return engine.SurfaceVertices.raw(mode, positions, + return engine.CkVertices.raw( + mode, + positions, + textureCoordinates: textureCoordinates, colors: colors, - indices: indices); + indices: indices, + ); + } + return engine.SurfaceVertices.raw( + mode, + positions, + colors: colors, + indices: indices, + ); } } -/// Records a [Picture] containing a sequence of graphical operations. -/// -/// To begin recording, construct a [Canvas] to record the commands. -/// To end recording, use the [PictureRecorder.endRecording] method. abstract class PictureRecorder { - /// Creates a new idle PictureRecorder. To associate it with a - /// [Canvas] and begin recording, pass this [PictureRecorder] to the - /// [Canvas] constructor. factory PictureRecorder() { if (engine.experimentalUseSkia) { return engine.CkPictureRecorder(); @@ -139,41 +79,10 @@ abstract class PictureRecorder { return engine.EnginePictureRecorder(); } } - - /// Whether this object is currently recording commands. - /// - /// Specifically, this returns true if a [Canvas] object has been - /// created to record commands and recording has not yet ended via a - /// call to [endRecording], and false if either this - /// [PictureRecorder] has not yet been associated with a [Canvas], - /// or the [endRecording] method has already been called. bool get isRecording; - - /// Finishes recording graphical operations. - /// - /// Returns a picture containing the graphical operations that have been - /// recorded thus far. After calling this function, both the picture recorder - /// and the canvas objects are invalid and cannot be used further. Picture endRecording(); } -/// An interface for recording graphical operations. -/// -/// [Canvas] objects are used in creating [Picture] objects, which can -/// themselves be used with a [SceneBuilder] to build a [Scene]. In -/// normal usage, however, this is all handled by the framework. -/// -/// A canvas has a current transformation matrix which is applied to all -/// operations. Initially, the transformation matrix is the identity transform. -/// It can be modified using the [translate], [scale], [rotate], [skew], -/// and [transform] methods. -/// -/// A canvas also has a current clip region which is applied to all operations. -/// Initially, the clip region is infinite. It can be modified using the -/// [clipRect], [clipRRect], and [clipPath] methods. -/// -/// The current transform and clip can be saved and restored using the stack -/// managed by the [save], [saveLayer], and [restore] methods. abstract class Canvas { factory Canvas(PictureRecorder recorder, [Rect? cullRect]) { if (engine.experimentalUseSkia) { @@ -182,472 +91,37 @@ abstract class Canvas { return engine.SurfaceCanvas(recorder as engine.EnginePictureRecorder, cullRect); } } - - /// Saves a copy of the current transform and clip on the save stack. - /// - /// Call [restore] to pop the save stack. - /// - /// See also: - /// - /// * [saveLayer], which does the same thing but additionally also groups the - /// commands done until the matching [restore]. void save(); - - /// Saves a copy of the current transform and clip on the save stack, and then - /// creates a new group which subsequent calls will become a part of. When the - /// save stack is later popped, the group will be flattened into a layer and - /// have the given `paint`'s [Paint.colorFilter] and [Paint.blendMode] - /// applied. - /// - /// This lets you create composite effects, for example making a group of - /// drawing commands semi-transparent. Without using [saveLayer], each part of - /// the group would be painted individually, so where they overlap would be - /// darker than where they do not. By using [saveLayer] to group them - /// together, they can be drawn with an opaque color at first, and then the - /// entire group can be made transparent using the [saveLayer]'s paint. - /// - /// Call [restore] to pop the save stack and apply the paint to the group. - /// - /// ## Using saveLayer with clips - /// - /// When a rectangular clip operation (from [clipRect]) is not axis-aligned - /// with the raster buffer, or when the clip operation is not rectalinear (e.g. - /// because it is a rounded rectangle clip created by [clipRRect] or an - /// arbitrarily complicated path clip created by [clipPath]), the edge of the - /// clip needs to be anti-aliased. - /// - /// If two draw calls overlap at the edge of such a clipped region, without - /// using [saveLayer], the first drawing will be anti-aliased with the - /// background first, and then the second will be anti-aliased with the result - /// of blending the first drawing and the background. On the other hand, if - /// [saveLayer] is used immediately after establishing the clip, the second - /// drawing will cover the first in the layer, and thus the second alone will - /// be anti-aliased with the background when the layer is clipped and - /// composited (when [restore] is called). - /// - /// For example, this [CustomPainter.paint] method paints a clean white - /// rounded rectangle: - /// - /// ```dart - /// void paint(Canvas canvas, Size size) { - /// Rect rect = Offset.zero & size; - /// canvas.save(); - /// canvas.clipRRect(new RRect.fromRectXY(rect, 100.0, 100.0)); - /// canvas.saveLayer(rect, new Paint()); - /// canvas.drawPaint(new Paint()..color = Colors.red); - /// canvas.drawPaint(new Paint()..color = Colors.white); - /// canvas.restore(); - /// canvas.restore(); - /// } - /// ``` - /// - /// On the other hand, this one renders a red outline, the result of the red - /// paint being anti-aliased with the background at the clip edge, then the - /// white paint being similarly anti-aliased with the background _including - /// the clipped red paint_: - /// - /// ```dart - /// void paint(Canvas canvas, Size size) { - /// // (this example renders poorly, prefer the example above) - /// Rect rect = Offset.zero & size; - /// canvas.save(); - /// canvas.clipRRect(new RRect.fromRectXY(rect, 100.0, 100.0)); - /// canvas.drawPaint(new Paint()..color = Colors.red); - /// canvas.drawPaint(new Paint()..color = Colors.white); - /// canvas.restore(); - /// } - /// ``` - /// - /// This point is moot if the clip only clips one draw operation. For example, - /// the following paint method paints a pair of clean white rounded - /// rectangles, even though the clips are not done on a separate layer: - /// - /// ```dart - /// void paint(Canvas canvas, Size size) { - /// canvas.save(); - /// canvas.clipRRect(new RRect.fromRectXY(Offset.zero & (size / 2.0), 50.0, 50.0)); - /// canvas.drawPaint(new Paint()..color = Colors.white); - /// canvas.restore(); - /// canvas.save(); - /// canvas.clipRRect(new RRect.fromRectXY(size.center(Offset.zero) & (size / 2.0), 50.0, 50.0)); - /// canvas.drawPaint(new Paint()..color = Colors.white); - /// canvas.restore(); - /// } - /// ``` - /// - /// (Incidentally, rather than using [clipRRect] and [drawPaint] to draw - /// rounded rectangles like this, prefer the [drawRRect] method. These - /// examples are using [drawPaint] as a proxy for "complicated draw operations - /// that will get clipped", to illustrate the point.) - /// - /// ## Performance considerations - /// - /// Generally speaking, [saveLayer] is relatively expensive. - /// - /// There are a several different hardware architectures for GPUs (graphics - /// processing units, the hardware that handles graphics), but most of them - /// involve batching commands and reordering them for performance. When layers - /// are used, they cause the rendering pipeline to have to switch render - /// target (from one layer to another). Render target switches can flush the - /// GPU's command buffer, which typically means that optimizations that one - /// could get with larger batching are lost. Render target switches also - /// generate a lot of memory churn because the GPU needs to copy out the - /// current frame buffer contents from the part of memory that's optimized for - /// writing, and then needs to copy it back in once the previous render target - /// (layer) is restored. - /// - /// See also: - /// - /// * [save], which saves the current state, but does not create a new layer - /// for subsequent commands. - /// * [BlendMode], which discusses the use of [Paint.blendMode] with - /// [saveLayer]. void saveLayer(Rect? bounds, Paint paint); - - /// Pops the current save stack, if there is anything to pop. - /// Otherwise, does nothing. - /// - /// Use [save] and [saveLayer] to push state onto the stack. - /// - /// If the state was pushed with with [saveLayer], then this call will also - /// cause the new layer to be composited into the previous layer. void restore(); - - /// Returns the number of items on the save stack, including the - /// initial state. This means it returns 1 for a clean canvas, and - /// that each call to [save] and [saveLayer] increments it, and that - /// each matching call to [restore] decrements it. - /// - /// This number cannot go below 1. int getSaveCount(); - - /// Add a translation to the current transform, shifting the coordinate space - /// horizontally by the first argument and vertically by the second argument. void translate(double dx, double dy); - - /// Add an axis-aligned scale to the current transform, scaling by the first - /// argument in the horizontal direction and the second in the vertical - /// direction. - /// - /// If [sy] is unspecified, [sx] will be used for the scale in both - /// directions. void scale(double sx, [double? sy]); - - /// Add a rotation to the current transform. The argument is in radians clockwise. void rotate(double radians); - - /// Add an axis-aligned skew to the current transform, with the first argument - /// being the horizontal skew in radians clockwise around the origin, and the - /// second argument being the vertical skew in radians clockwise around the - /// origin. void skew(double sx, double sy); - - /// Multiply the current transform by the specified 4⨉4 transformation matrix - /// specified as a list of values in column-major order. void transform(Float64List matrix4); - - /// Reduces the clip region to the intersection of the current clip and the - /// given rectangle. - /// - /// If [doAntiAlias] is true, then the clip will be anti-aliased. - /// - /// If multiple draw commands intersect with the clip boundary, this can result - /// in incorrect blending at the clip boundary. See [saveLayer] for a - /// discussion of how to address that. - /// - /// Use [ClipOp.difference] to subtract the provided rectangle from the - /// current clip. - void clipRect(Rect rect, - {ClipOp clipOp = ClipOp.intersect, bool doAntiAlias = true}); - - /// Reduces the clip region to the intersection of the current clip and the - /// given rounded rectangle. - /// - /// If [doAntiAlias] is true, then the clip will be anti-aliased. - /// - /// If multiple draw commands intersect with the clip boundary, this can result - /// in incorrect blending at the clip boundary. See [saveLayer] for a - /// discussion of how to address that and some examples of using [clipRRect]. + void clipRect(Rect rect, {ClipOp clipOp = ClipOp.intersect, bool doAntiAlias = true}); void clipRRect(RRect rrect, {bool doAntiAlias = true}); - - /// Reduces the clip region to the intersection of the current clip and the - /// given [Path]. - /// - /// If [doAntiAlias] is true, then the clip will be anti-aliased. - /// - /// If multiple draw commands intersect with the clip boundary, this can result - /// multiple draw commands intersect with the clip boundary, this can result - /// in incorrect blending at the clip boundary. See [saveLayer] for a - /// discussion of how to address that. void clipPath(Path path, {bool doAntiAlias = true}); - - /// Paints the given [Color] onto the canvas, applying the given - /// [BlendMode], with the given color being the source and the background - /// being the destination. void drawColor(Color color, BlendMode blendMode); - - /// Draws a line between the given points using the given paint. The line is - /// stroked, the value of the [Paint.style] is ignored for this call. - /// - /// The `p1` and `p2` arguments are interpreted as offsets from the origin. void drawLine(Offset p1, Offset p2, Paint paint); - - /// Fills the canvas with the given [Paint]. - /// - /// To fill the canvas with a solid color and blend mode, consider - /// [drawColor] instead. void drawPaint(Paint paint); - - /// Draws a rectangle with the given [Paint]. Whether the rectangle is filled - /// or stroked (or both) is controlled by [Paint.style]. void drawRect(Rect rect, Paint paint); - - /// Draws a rounded rectangle with the given [Paint]. Whether the rectangle is - /// filled or stroked (or both) is controlled by [Paint.style]. void drawRRect(RRect rrect, Paint paint); - - /// Draws a shape consisting of the difference between two rounded rectangles - /// with the given [Paint]. Whether this shape is filled or stroked (or both) - /// is controlled by [Paint.style]. - /// - /// This shape is almost but not quite entirely unlike an annulus. void drawDRRect(RRect outer, RRect inner, Paint paint); - - /// Draws an axis-aligned oval that fills the given axis-aligned rectangle - /// with the given [Paint]. Whether the oval is filled or stroked (or both) is - /// controlled by [Paint.style]. void drawOval(Rect rect, Paint paint); - - /// Draws a circle centered at the point given by the first argument and - /// that has the radius given by the second argument, with the [Paint] given in - /// the third argument. Whether the circle is filled or stroked (or both) is - /// controlled by [Paint.style]. void drawCircle(Offset c, double radius, Paint paint); - - /// Draw an arc scaled to fit inside the given rectangle. It starts from - /// startAngle radians around the oval up to startAngle + sweepAngle - /// radians around the oval, with zero radians being the point on - /// the right hand side of the oval that crosses the horizontal line - /// that intersects the center of the rectangle and with positive - /// angles going clockwise around the oval. If useCenter is true, the arc is - /// closed back to the center, forming a circle sector. Otherwise, the arc is - /// not closed, forming a circle segment. - /// - /// This method is optimized for drawing arcs and should be faster than [Path.arcTo]. - void drawArc(Rect rect, double startAngle, double sweepAngle, bool useCenter, - Paint paint); - - /// Draws the given [Path] with the given [Paint]. Whether this shape is - /// filled or stroked (or both) is controlled by [Paint.style]. If the path is - /// filled, then subpaths within it are implicitly closed (see [Path.close]). + void drawArc(Rect rect, double startAngle, double sweepAngle, bool useCenter, Paint paint); void drawPath(Path path, Paint paint); - - /// Draws the given [Image] into the canvas with its top-left corner at the - /// given [Offset]. The image is composited into the canvas using the given [Paint]. void drawImage(Image image, Offset offset, Paint paint); - - /// Draws the subset of the given image described by the `src` argument into - /// the canvas in the axis-aligned rectangle given by the `dst` argument. - /// - /// This might sample from outside the `src` rect by up to half the width of - /// an applied filter. - /// - /// Multiple calls to this method with different arguments (from the same - /// image) can be batched into a single call to [drawAtlas] to improve - /// performance. void drawImageRect(Image image, Rect src, Rect dst, Paint paint); - - /// Draws the given [Image] into the canvas using the given [Paint]. - /// - /// The image is drawn in nine portions described by splitting the image by - /// drawing two horizontal lines and two vertical lines, where the `center` - /// argument describes the rectangle formed by the four points where these - /// four lines intersect each other. (This forms a 3-by-3 grid of regions, - /// the center region being described by the `center` argument.) - /// - /// The four regions in the corners are drawn, without scaling, in the four - /// corners of the destination rectangle described by `dst`. The remaining - /// five regions are drawn by stretching them to fit such that they exactly - /// cover the destination rectangle while maintaining their relative - /// positions. void drawImageNine(Image image, Rect center, Rect dst, Paint paint); - - /// Draw the given picture onto the canvas. To create a picture, see - /// [PictureRecorder]. void drawPicture(Picture picture); - - /// Draws the text in the given [Paragraph] into this canvas at the given - /// [Offset]. - /// - /// The [Paragraph] object must have had [Paragraph.layout] called on it - /// first. - /// - /// To align the text, set the `textAlign` on the [ParagraphStyle] object - /// passed to the [new ParagraphBuilder] constructor. For more details see - /// [TextAlign] and the discussion at [new ParagraphStyle]. - /// - /// If the text is left aligned or justified, the left margin will be at the - /// position specified by the `offset` argument's [Offset.dx] coordinate. - /// - /// If the text is right aligned or justified, the right margin will be at the - /// position described by adding the [ParagraphConstraints.width] given to - /// [Paragraph.layout], to the `offset` argument's [Offset.dx] coordinate. - /// - /// If the text is centered, the centering axis will be at the position - /// described by adding half of the [ParagraphConstraints.width] given to - /// [Paragraph.layout], to the `offset` argument's [Offset.dx] coordinate. void drawParagraph(Paragraph paragraph, Offset offset); - - /// Draws a sequence of points according to the given [PointMode]. - /// - /// The `points` argument is interpreted as offsets from the origin. - /// - /// See also: - /// - /// * [drawRawPoints], which takes `points` as a [Float32List] rather than a - /// [List]. void drawPoints(PointMode pointMode, List points, Paint paint); - - /// Draws a sequence of points according to the given [PointMode]. - /// - /// The `points` argument is interpreted as a list of pairs of floating point - /// numbers, where each pair represents an x and y offset from the origin. - /// - /// See also: - /// - /// * [drawPoints], which takes `points` as a [List] rather than a - /// [List]. void drawRawPoints(PointMode pointMode, Float32List points, Paint paint); void drawVertices(Vertices vertices, BlendMode blendMode, Paint paint); - - /// Draws many parts of an image - the [atlas] - onto the canvas. - /// - /// This method allows for optimization when you want to draw many parts of an - /// image onto the canvas, such as when using sprites or zooming. It is more efficient - /// than using multiple calls to [drawImageRect] and provides more functionality - /// to individually transform each image part by a separate rotation or scale and - /// blend or modulate those parts with a solid color. - /// - /// The method takes a list of [Rect] objects that each define a piece of the - /// [atlas] image to be drawn independently. Each [Rect] is associated with an - /// [RSTransform] entry in the [transforms] list which defines the location, - /// rotation, and (uniform) scale with which to draw that portion of the image. - /// Each [Rect] can also be associated with an optional [Color] which will be - /// composed with the associated image part using the [blendMode] before blending - /// the result onto the canvas. The full operation can be broken down as: - /// - /// - Blend each rectangular portion of the image specified by an entry in the - /// [rects] argument with its associated entry in the [colors] list using the - /// [blendMode] argument (if a color is specified). In this part of the operation, - /// the image part will be considered the source of the operation and the associated - /// color will be considered the destination. - /// - Blend the result from the first step onto the canvas using the translation, - /// rotation, and scale properties expressed in the associated entry in the - /// [transforms] list using the properties of the [Paint] object. - /// - /// If the first stage of the operation which blends each part of the image with - /// a color is needed, then both the [colors] and [blendMode] arguments must - /// not be null and there must be an entry in the [colors] list for each - /// image part. If that stage is not needed, then the [colors] argument can - /// be either null or an empty list and the [blendMode] argument may also be null. - /// - /// The optional [cullRect] argument can provide an estimate of the bounds of the - /// coordinates rendered by all components of the atlas to be compared against - /// the clip to quickly reject the operation if it does not intersect. - /// - /// An example usage to render many sprites from a single sprite atlas with no - /// rotations or scales: - /// - /// ```dart - /// class Sprite { - /// int index; - /// double centerX; - /// double centerY; - /// } - /// - /// class MyPainter extends CustomPainter { - /// // assume spriteAtlas contains N 10x10 sprites side by side in a (N*10)x10 image - /// ui.Image spriteAtlas; - /// List allSprites; - /// - /// @override - /// void paint(Canvas canvas, Size size) { - /// Paint paint = Paint(); - /// canvas.drawAtlas(spriteAtlas, [ - /// for (Sprite sprite in allSprites) - /// RSTransform.fromComponents( - /// rotation: 0.0, - /// scale: 1.0, - /// // Center of the sprite relative to its rect - /// anchorX: 5.0, - /// anchorY: 5.0, - /// // Location at which to draw the center of the sprite - /// translateX: sprite.centerX, - /// translateY: sprite.centerY, - /// ), - /// ], [ - /// for (Sprite sprite in allSprites) - /// Rect.fromLTWH(sprite.index * 10.0, 0.0, 10.0, 10.0), - /// ], null, null, null, paint); - /// } - /// - /// ... - /// } - /// ``` - /// - /// Another example usage which renders sprites with an optional opacity and rotation: - /// - /// ```dart - /// class Sprite { - /// int index; - /// double centerX; - /// double centerY; - /// int alpha; - /// double rotation; - /// } - /// - /// class MyPainter extends CustomPainter { - /// // assume spriteAtlas contains N 10x10 sprites side by side in a (N*10)x10 image - /// ui.Image spriteAtlas; - /// List allSprites; - /// - /// @override - /// void paint(Canvas canvas, Size size) { - /// Paint paint = Paint(); - /// canvas.drawAtlas(spriteAtlas, [ - /// for (Sprite sprite in allSprites) - /// RSTransform.fromComponents( - /// rotation: sprite.rotation, - /// scale: 1.0, - /// // Center of the sprite relative to its rect - /// anchorX: 5.0, - /// anchorY: 5.0, - /// // Location at which to draw the center of the sprite - /// translateX: sprite.centerX, - /// translateY: sprite.centerY, - /// ), - /// ], [ - /// for (Sprite sprite in allSprites) - /// Rect.fromLTWH(sprite.index * 10.0, 0.0, 10.0, 10.0), - /// ], [ - /// for (Sprite sprite in allSprites) - /// Color.white.withAlpha(sprite.alpha), - /// ], BlendMode.srcIn, null, paint); - /// } - /// - /// ... - /// } - /// ``` - /// - /// The length of the [transforms] and [rects] lists must be equal and - /// if the [colors] argument is not null then it must either be empty or - /// have the same length as the other two lists. - /// - /// See also: - /// - /// * [drawRawAtlas], which takes its arguments as typed data lists rather - /// than objects. void drawAtlas( Image atlas, List transforms, @@ -657,148 +131,6 @@ abstract class Canvas { Rect? cullRect, Paint paint, ); - - /// Draws many parts of an image - the [atlas] - onto the canvas. - /// - /// This method allows for optimization when you want to draw many parts of an - /// image onto the canvas, such as when using sprites or zooming. It is more efficient - /// than using multiple calls to [drawImageRect] and provides more functionality - /// to individually transform each image part by a separate rotation or scale and - /// blend or modulate those parts with a solid color. It is also more efficient - /// than [drawAtlas] as the data in the arguments is already packed in a format - /// that can be directly used by the rendering code. - /// - /// A full description of how this method uses its arguments to draw onto the - /// canvas can be found in the description of the [drawAtlas] method. - /// - /// The [rstTransforms] argument is interpreted as a list of four-tuples, with - /// each tuple being ([RSTransform.scos], [RSTransform.ssin], - /// [RSTransform.tx], [RSTransform.ty]). - /// - /// The [rects] argument is interpreted as a list of four-tuples, with each - /// tuple being ([Rect.left], [Rect.top], [Rect.right], [Rect.bottom]). - /// - /// The [colors] argument, which can be null, is interpreted as a list of - /// 32-bit colors, with the same packing as [Color.value]. If the [colors] - /// argument is not null then the [blendMode] argument must also not be null. - /// - /// An example usage to render many sprites from a single sprite atlas with no rotations - /// or scales: - /// - /// ```dart - /// class Sprite { - /// int index; - /// double centerX; - /// double centerY; - /// } - /// - /// class MyPainter extends CustomPainter { - /// // assume spriteAtlas contains N 10x10 sprites side by side in a (N*10)x10 image - /// ui.Image spriteAtlas; - /// List allSprites; - /// - /// @override - /// void paint(Canvas canvas, Size size) { - /// // For best advantage, these lists should be cached and only specific - /// // entries updated when the sprite information changes. This code is - /// // illustrative of how to set up the data and not a recommendation for - /// // optimal usage. - /// Float32List rectList = Float32List(allSprites.length * 4); - /// Float32List transformList = Float32List(allSprites.length * 4); - /// for (int i = 0; i < allSprites.length; i++) { - /// final double rectX = sprite.spriteIndex * 10.0; - /// rectList[i * 4 + 0] = rectX; - /// rectList[i * 4 + 1] = 0.0; - /// rectList[i * 4 + 2] = rectX + 10.0; - /// rectList[i * 4 + 3] = 10.0; - /// - /// // This example sets the RSTransform values directly for a common case of no - /// // rotations or scales and just a translation to position the atlas entry. For - /// // more complicated transforms one could use the RSTransform class to compute - /// // the necessary values or do the same math directly. - /// transformList[i * 4 + 0] = 1.0; - /// transformList[i * 4 + 1] = 0.0; - /// transformList[i * 4 + 2] = sprite.centerX - 5.0; - /// transformList[i * 4 + 2] = sprite.centerY - 5.0; - /// } - /// Paint paint = Paint(); - /// canvas.drawAtlas(spriteAtlas, transformList, rectList, null, null, null, paint); - /// } - /// - /// ... - /// } - /// ``` - /// - /// Another example usage which renders sprites with an optional opacity and rotation: - /// - /// ```dart - /// class Sprite { - /// int index; - /// double centerX; - /// double centerY; - /// int alpha; - /// double rotation; - /// } - /// - /// class MyPainter extends CustomPainter { - /// // assume spriteAtlas contains N 10x10 sprites side by side in a (N*10)x10 image - /// ui.Image spriteAtlas; - /// List allSprites; - /// - /// @override - /// void paint(Canvas canvas, Size size) { - /// // For best advantage, these lists should be cached and only specific - /// // entries updated when the sprite information changes. This code is - /// // illustrative of how to set up the data and not a recommendation for - /// // optimal usage. - /// Float32List rectList = Float32List(allSprites.length * 4); - /// Float32List transformList = Float32List(allSprites.length * 4); - /// Int32List colorList = Int32List(allSprites.length); - /// for (int i = 0; i < allSprites.length; i++) { - /// final double rectX = sprite.spriteIndex * 10.0; - /// rectList[i * 4 + 0] = rectX; - /// rectList[i * 4 + 1] = 0.0; - /// rectList[i * 4 + 2] = rectX + 10.0; - /// rectList[i * 4 + 3] = 10.0; - /// - /// // This example uses an RSTransform object to compute the necessary values for - /// // the transform using a factory helper method because the sprites contain - /// // rotation values which are not trivial to work with. But if the math for the - /// // values falls out from other calculations on the sprites then the values could - /// // possibly be generated directly from the sprite update code. - /// final RSTransform transform = RSTransform.fromComponents( - /// rotation: sprite.rotation, - /// scale: 1.0, - /// // Center of the sprite relative to its rect - /// anchorX: 5.0, - /// anchorY: 5.0, - /// // Location at which to draw the center of the sprite - /// translateX: sprite.centerX, - /// translateY: sprite.centerY, - /// ); - /// transformList[i * 4 + 0] = transform.scos; - /// transformList[i * 4 + 1] = transform.ssin; - /// transformList[i * 4 + 2] = transform.tx; - /// transformList[i * 4 + 2] = transform.ty; - /// - /// // This example computes the color value directly, but one could also compute - /// // an actual Color object and use its Color.value getter for the same result. - /// // Since we are using BlendMode.srcIn, only the alpha component matters for - /// // these colors which makes this a simple shift operation. - /// colorList[i] = sprite.alpha << 24; - /// } - /// Paint paint = Paint(); - /// canvas.drawAtlas(spriteAtlas, transformList, rectList, colorList, BlendMode.srcIn, null, paint); - /// } - /// - /// ... - /// } - /// ``` - /// - /// See also: - /// - /// * [drawAtlas], which takes its arguments as objects rather than typed - /// data lists. void drawRawAtlas( Image atlas, Float32List rstTransforms, @@ -808,13 +140,6 @@ abstract class Canvas { Rect? cullRect, Paint paint, ); - - /// Draws a shadow for a [Path] representing the given material elevation. - /// - /// The `transparentOccluder` argument should be true if the occluding object - /// is not opaque. - /// - /// The arguments must not be null. void drawShadow( Path path, Color color, @@ -823,116 +148,22 @@ abstract class Canvas { ); } -/// An object representing a sequence of recorded graphical operations. -/// -/// To create a [Picture], use a [PictureRecorder]. -/// -/// A [Picture] can be placed in a [Scene] using a [SceneBuilder], via -/// the [SceneBuilder.addPicture] method. A [Picture] can also be -/// drawn into a [Canvas], using the [Canvas.drawPicture] method. abstract class Picture { - /// Creates an image from this picture. - /// - /// The returned image will be `width` pixels wide and `height` pixels high. - /// The picture is rasterized within the 0 (left), 0 (top), `width` (right), - /// `height` (bottom) bounds. Content outside these bounds is clipped. - /// - /// Although the image is returned synchronously, the picture is actually - /// rasterized the first time the image is drawn and then cached. Future toImage(int width, int height); - - /// Release the resources used by this object. The object is no longer usable - /// after this method is called. void dispose(); - - /// Returns the approximate number of bytes allocated for this object. - /// - /// The actual size of this picture may be larger, particularly if it contains - /// references to image or other large objects. int get approximateBytesUsed; } -/// Determines the winding rule that decides how the interior of a [Path] is -/// calculated. -/// -/// This enum is used by the [Path.fillType] property. enum PathFillType { - /// The interior is defined by a non-zero sum of signed edge crossings. - /// - /// For a given point, the point is considered to be on the inside of the path - /// if a line drawn from the point to infinity crosses lines going clockwise - /// around the point a different number of times than it crosses lines going - /// counter-clockwise around that point. - /// - /// See: nonZero, - - /// The interior is defined by an odd number of edge crossings. - /// - /// For a given point, the point is considered to be on the inside of the path - /// if a line drawn from the point to infinity crosses an odd number of lines. - /// - /// See: evenOdd, } - -/// Strategies for combining paths. -/// -/// See also: -/// -/// * [Path.combine], which uses this enum to decide how to combine two paths. // Must be kept in sync with SkPathOp + enum PathOperation { - /// Subtract the second path from the first path. - /// - /// For example, if the two paths are overlapping circles of equal diameter - /// but differing centers, the result would be a crescent portion of the - /// first circle that was not overlapped by the second circle. - /// - /// See also: - /// - /// * [reverseDifference], which is the same but subtracting the first path - /// from the second. difference, - - /// Create a new path that is the intersection of the two paths, leaving the - /// overlapping pieces of the path. - /// - /// For example, if the two paths are overlapping circles of equal diameter - /// but differing centers, the result would be only the overlapping portion - /// of the two circles. - /// - /// See also: - /// * [xor], which is the inverse of this operation intersect, - - /// Create a new path that is the union (inclusive-or) of the two paths. - /// - /// For example, if the two paths are overlapping circles of equal diameter - /// but differing centers, the result would be a figure-eight like shape - /// matching the outer boundaries of both circles. union, - - /// Create a new path that is the exclusive-or of the two paths, leaving - /// everything but the overlapping pieces of the path. - /// - /// For example, if the two paths are overlapping circles of equal diameter - /// but differing centers, the figure-eight like shape less the overlapping - /// parts - /// - /// See also: - /// * [intersect], which is the inverse of this operation xor, - - /// Subtract the first path from the second path. - /// - /// For example, if the two paths are overlapping circles of equal diameter - /// but differing centers, the result would be a crescent portion of the - /// second circle that was not overlapped by the first circle. - /// - /// See also: - /// - /// * [difference], which is the same but subtracting the second path - /// from the first. reverseDifference, } diff --git a/engine/src/flutter/lib/web_ui/lib/src/ui/channel_buffers.dart b/engine/src/flutter/lib/web_ui/lib/src/ui/channel_buffers.dart index fa587a907a..2dc98120bd 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/ui/channel_buffers.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/ui/channel_buffers.dart @@ -5,50 +5,27 @@ // @dart = 2.10 part of ui; -/// A saved platform message for a channel with its callback. class _StoredMessage { - /// Default constructor, takes in a [ByteData] that represents the - /// payload of the message and a [PlatformMessageResponseCallback] - /// that represents the callback that will be called when the message - /// is handled. _StoredMessage(this._data, this._callback); - - /// Representation of the message's payload. final ByteData? _data; ByteData? get data => _data; - - /// Callback to be called when the message is received. final PlatformMessageResponseCallback _callback; PlatformMessageResponseCallback get callback => _callback; } -/// A fixed-size circular queue. class _RingBuffer { - /// The underlying data for the RingBuffer. ListQueues dynamically resize, - /// [_RingBuffer]s do not. final collection.ListQueue _queue; - _RingBuffer(this._capacity) - : _queue = collection.ListQueue(_capacity); - - /// Returns the number of items in the [_RingBuffer]. + _RingBuffer(this._capacity) : _queue = collection.ListQueue(_capacity); int get length => _queue.length; - - /// The number of items that can be stored in the [_RingBuffer]. int _capacity; int get capacity => _capacity; - - /// Returns true if there are no items in the [_RingBuffer]. bool get isEmpty => _queue.isEmpty; - - /// A callback that get's called when items are ejected from the [_RingBuffer] - /// by way of an overflow or a resizing. Function(T)? _dropItemCallback; set dropItemCallback(Function(T) callback) { _dropItemCallback = callback; } - /// Returns true on overflow. bool push(T val) { if (_capacity <= 0) { return true; @@ -59,13 +36,10 @@ class _RingBuffer { } } - /// Returns null when empty. T? pop() { return _queue.isEmpty ? null : _queue.removeFirst(); } - /// Removes items until then length reaches [lengthLimit] and returns - /// the number of items removed. int _dropOverflowItems(int lengthLimit) { int result = 0; while (_queue.length > lengthLimit) { @@ -76,46 +50,20 @@ class _RingBuffer { return result; } - /// Returns the number of discarded items resulting from resize. int resize(int newSize) { _capacity = newSize; return _dropOverflowItems(newSize); } } -/// Signature for [ChannelBuffers.drain]. typedef DrainChannelCallback = Future Function(ByteData?, PlatformMessageResponseCallback); -/// Storage of channel messages until the channels are completely routed, -/// i.e. when a message handler is attached to the channel on the framework side. -/// -/// Each channel has a finite buffer capacity and in a FIFO manner messages will -/// be deleted if the capacity is exceeded. The intention is that these buffers -/// will be drained once a callback is setup on the BinaryMessenger in the -/// Flutter framework. -/// -/// Clients of Flutter shouldn't need to allocate their own ChannelBuffers -/// and should only access this package's [channelBuffers] if they are writing -/// their own custom [BinaryMessenger]. class ChannelBuffers { - /// By default we store one message per channel. There are tradeoffs associated - /// with any size. The correct size should be chosen for the semantics of your - /// channel. - /// - /// Size 0 implies you want to ignore any message that gets sent before the engine - /// is ready (keeping in mind there is no way to know when the engine is ready). - /// - /// Size 1 implies that you only care about the most recent value. - /// - /// Size >1 means you want to process every single message and want to chose a - /// buffer size that will avoid any overflows. static const int kDefaultBufferSize = 1; static const String kControlChannelName = 'dev.flutter/channel-buffers'; - - /// A mapping between a channel name and its associated [_RingBuffer]. final Map?> _messages = - ?>{}; + ?>{}; _RingBuffer<_StoredMessage> _makeRingBuffer(int size) { final _RingBuffer<_StoredMessage> result = _RingBuffer<_StoredMessage>(size); @@ -127,7 +75,6 @@ class ChannelBuffers { message.callback(null); } - /// Returns true on overflow. bool push(String channel, ByteData? data, PlatformMessageResponseCallback callback) { _RingBuffer<_StoredMessage>? queue = _messages[channel]; if (queue == null) { @@ -147,7 +94,6 @@ class ChannelBuffers { return didOverflow; } - /// Returns null on underflow. _StoredMessage? _pop(String channel) { final _RingBuffer<_StoredMessage>? queue = _messages[channel]; final _StoredMessage? result = queue?.pop(); @@ -159,10 +105,6 @@ class ChannelBuffers { return (queue == null) ? true : queue.isEmpty; } - /// Changes the capacity of the queue associated with the given channel. - /// - /// This could result in the dropping of messages if newSize is less - /// than the current length of the queue. void _resize(String channel, int newSize) { _RingBuffer<_StoredMessage>? queue = _messages[channel]; if (queue == null) { @@ -176,10 +118,6 @@ class ChannelBuffers { } } - /// Remove and process all stored messages for a given channel. - /// - /// This should be called once a channel is prepared to handle messages - /// (i.e. when a message handler is setup in the framework). Future drain(String channel, DrainChannelCallback callback) async { while (!_isEmpty(channel)) { final _StoredMessage message = _pop(channel)!; @@ -193,15 +131,6 @@ class ChannelBuffers { return utf8.decode(list); } - /// Handle a control message. - /// - /// This is intended to be called by the platform messages dispatcher. - /// - /// Available messages: - /// - Name: resize - /// Arity: 2 - /// Format: `resize\r\r` - /// Description: Allows you to set the size of a channel's buffer. void handleMessage(ByteData data) { final List command = _getString(data).split('\r'); if (command.length == /*arity=*/2 + 1 && command[0] == 'resize') { @@ -212,10 +141,4 @@ class ChannelBuffers { } } -/// [ChannelBuffer]s that allow the storage of messages between the -/// Engine and the Framework. Typically messages that can't be delivered -/// are stored here until the Framework is able to process them. -/// -/// See also: -/// * [BinaryMessenger] - The place where ChannelBuffers are typically read. final ChannelBuffers channelBuffers = ChannelBuffers(); diff --git a/engine/src/flutter/lib/web_ui/lib/src/ui/compositing.dart b/engine/src/flutter/lib/web_ui/lib/src/ui/compositing.dart index 11a0e1199d..665ebbe14c 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/ui/compositing.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/ui/compositing.dart @@ -5,113 +5,34 @@ // @dart = 2.10 part of ui; -/// An opaque object representing a composited scene. -/// -/// To create a Scene object, use a [SceneBuilder]. -/// -/// Scene objects can be displayed on the screen using the -/// [Window.render] method. abstract class Scene { - /// Creates a raster image representation of the current state of the scene. - /// This is a slow operation that is performed on a background thread. Future toImage(int width, int height); - - /// Releases the resources used by this scene. - /// - /// After calling this function, the scene is cannot be used further. void dispose(); } -/// An opaque handle to a transform engine layer. -/// -/// Instances of this class are created by [SceneBuilder.pushTransform]. -/// -/// {@template dart.ui.sceneBuilder.oldLayerCompatibility} -/// `oldLayer` parameter in [SceneBuilder] methods only accepts objects created -/// by the engine. [SceneBuilder] will throw an [AssertionError] if you pass it -/// a custom implementation of this class. -/// {@endtemplate} abstract class TransformEngineLayer implements EngineLayer {} -/// An opaque handle to an offset engine layer. -/// -/// Instances of this class are created by [SceneBuilder.pushOffset]. -/// -/// {@macro dart.ui.sceneBuilder.oldLayerCompatibility} abstract class OffsetEngineLayer implements EngineLayer {} -/// An opaque handle to a clip rect engine layer. -/// -/// Instances of this class are created by [SceneBuilder.pushClipRect]. -/// -/// {@macro dart.ui.sceneBuilder.oldLayerCompatibility} abstract class ClipRectEngineLayer implements EngineLayer {} -/// An opaque handle to a clip rounded rect engine layer. -/// -/// Instances of this class are created by [SceneBuilder.pushClipRRect]. -/// -/// {@macro dart.ui.sceneBuilder.oldLayerCompatibility} abstract class ClipRRectEngineLayer implements EngineLayer {} -/// An opaque handle to a clip path engine layer. -/// -/// Instances of this class are created by [SceneBuilder.pushClipPath]. -/// -/// {@macro dart.ui.sceneBuilder.oldLayerCompatibility} abstract class ClipPathEngineLayer implements EngineLayer {} -/// An opaque handle to an opacity engine layer. -/// -/// Instances of this class are created by [SceneBuilder.pushOpacity]. -/// -/// {@macro dart.ui.sceneBuilder.oldLayerCompatibility} abstract class OpacityEngineLayer implements EngineLayer {} -/// An opaque handle to a color filter engine layer. -/// -/// Instances of this class are created by [SceneBuilder.pushColorFilter]. -/// -/// {@macro dart.ui.sceneBuilder.oldLayerCompatibility} abstract class ColorFilterEngineLayer implements EngineLayer {} -/// An opaque handle to an image filter engine layer. -/// -/// Instances of this class are created by [SceneBuilder.pushImageFilter]. -/// -/// {@macro dart.ui.sceneBuilder.oldLayerCompatibility} abstract class ImageFilterEngineLayer implements EngineLayer {} -/// An opaque handle to a backdrop filter engine layer. -/// -/// Instances of this class are created by [SceneBuilder.pushBackdropFilter]. -/// -/// {@macro dart.ui.sceneBuilder.oldLayerCompatibility} abstract class BackdropFilterEngineLayer implements EngineLayer {} -/// An opaque handle to a shader mask engine layer. -/// -/// Instances of this class are created by [SceneBuilder.pushShaderMask]. -/// -/// {@macro dart.ui.sceneBuilder.oldLayerCompatibility} abstract class ShaderMaskEngineLayer implements EngineLayer {} -/// An opaque handle to a physical shape engine layer. -/// -/// Instances of this class are created by [SceneBuilder.pushPhysicalShape]. -/// -/// {@macro dart.ui.sceneBuilder.oldLayerCompatibility} abstract class PhysicalShapeEngineLayer implements EngineLayer {} -/// Builds a [Scene] containing the given visuals. -/// -/// A [Scene] can then be rendered using [Window.render]. -/// -/// To draw graphical operations onto a [Scene], first create a -/// [Picture] using a [PictureRecorder] and a [Canvas], and then add -/// it to the scene using [addPicture]. abstract class SceneBuilder { - /// Creates an empty [SceneBuilder] object. factory SceneBuilder() { if (engine.experimentalUseSkia) { return engine.LayerSceneBuilder(); @@ -119,142 +40,53 @@ abstract class SceneBuilder { return engine.SurfaceSceneBuilder(); } } - - /// Pushes an offset operation onto the operation stack. - /// - /// This is equivalent to [pushTransform] with a matrix with only translation. - /// - /// See [pop] for details about the operation stack. OffsetEngineLayer? pushOffset( double dx, double dy, { OffsetEngineLayer? oldLayer, }); - - /// Pushes a transform operation onto the operation stack. - /// - /// The objects are transformed by the given matrix before rasterization. - /// - /// See [pop] for details about the operation stack. TransformEngineLayer? pushTransform( Float64List matrix4, { TransformEngineLayer? oldLayer, }); - - /// Pushes a rectangular clip operation onto the operation stack. - /// - /// Rasterization outside the given rectangle is discarded. - /// - /// See [pop] for details about the operation stack, and [Clip] for different clip modes. - /// By default, the clip will be anti-aliased (clip = [Clip.antiAlias]). ClipRectEngineLayer? pushClipRect( Rect rect, { Clip clipBehavior = Clip.antiAlias, ClipRectEngineLayer? oldLayer, }); - - /// Pushes a rounded-rectangular clip operation onto the operation stack. - /// - /// Rasterization outside the given rounded rectangle is discarded. - /// - /// See [pop] for details about the operation stack. ClipRRectEngineLayer? pushClipRRect( RRect rrect, { required Clip clipBehavior, ClipRRectEngineLayer? oldLayer, }); - - /// Pushes a path clip operation onto the operation stack. - /// - /// Rasterization outside the given path is discarded. - /// - /// See [pop] for details about the operation stack. ClipPathEngineLayer? pushClipPath( Path path, { Clip clipBehavior = Clip.antiAlias, ClipPathEngineLayer? oldLayer, }); - - /// Pushes an opacity operation onto the operation stack. - /// - /// The given alpha value is blended into the alpha value of the objects' - /// rasterization. An alpha value of 0 makes the objects entirely invisible. - /// An alpha value of 255 has no effect (i.e., the objects retain the current - /// opacity). - /// - /// See [pop] for details about the operation stack. OpacityEngineLayer? pushOpacity( int alpha, { Offset offset = Offset.zero, OpacityEngineLayer? oldLayer, }); - - /// Pushes a color filter operation onto the operation stack. - /// - /// The given color is applied to the objects' rasterization using the given - /// blend mode. - /// - /// {@macro dart.ui.sceneBuilder.oldLayer} - /// - /// {@macro dart.ui.sceneBuilder.oldLayerVsRetained} - /// - /// See [pop] for details about the operation stack. ColorFilterEngineLayer? pushColorFilter( ColorFilter filter, { ColorFilterEngineLayer? oldLayer, }); - - /// Pushes an image filter operation onto the operation stack. - /// - /// The given filter is applied to the children's rasterization before compositing them into - /// the scene. - /// - /// {@macro dart.ui.sceneBuilder.oldLayer} - /// - /// {@macro dart.ui.sceneBuilder.oldLayerVsRetained} - /// - /// See [pop] for details about the operation stack. ImageFilterEngineLayer? pushImageFilter( ImageFilter filter, { ImageFilterEngineLayer? oldLayer, }); - - /// Pushes a backdrop filter operation onto the operation stack. - /// - /// The given filter is applied to the current contents of the scene prior to - /// rasterizing the given objects. - /// - /// See [pop] for details about the operation stack. BackdropFilterEngineLayer? pushBackdropFilter( ImageFilter filter, { BackdropFilterEngineLayer? oldLayer, }); - - /// Pushes a shader mask operation onto the operation stack. - /// - /// The given shader is applied to the object's rasterization in the given - /// rectangle using the given blend mode. - /// - /// See [pop] for details about the operation stack. ShaderMaskEngineLayer? pushShaderMask( Shader shader, Rect maskRect, BlendMode blendMode, { ShaderMaskEngineLayer? oldLayer, }); - - /// Pushes a physical layer operation for an arbitrary shape onto the - /// operation stack. - /// - /// By default, the layer's content will not be clipped (clip = [Clip.none]). - /// If clip equals [Clip.hardEdge], [Clip.antiAlias], or [Clip.antiAliasWithSaveLayer], - /// then the content is clipped to the given shape defined by [path]. - /// - /// If [elevation] is greater than 0.0, then a shadow is drawn around the layer. - /// [shadowColor] defines the color of the shadow if present and [color] defines the - /// color of the layer background. - /// - /// See [pop] for details about the operation stack, and [Clip] for different clip modes. PhysicalShapeEngineLayer? pushPhysicalShape({ required Path path, required double elevation, @@ -263,64 +95,15 @@ abstract class SceneBuilder { Clip clipBehavior = Clip.none, PhysicalShapeEngineLayer? oldLayer, }); - - /// Add a retained engine layer subtree from previous frames. - /// - /// All the engine layers that are in the subtree of the retained layer will - /// be automatically appended to the current engine layer tree. - /// - /// Therefore, when implementing a subclass of the [Layer] concept defined in - /// the rendering layer of Flutter's framework, once this is called, there's - /// no need to call [addToScene] for its children layers. void addRetained(EngineLayer retainedLayer); - - /// Ends the effect of the most recently pushed operation. - /// - /// Internally the scene builder maintains a stack of operations. Each of the - /// operations in the stack applies to each of the objects added to the scene. - /// Calling this function removes the most recently added operation from the - /// stack. void pop(); - - /// Adds an object to the scene that displays performance statistics. - /// - /// Useful during development to assess the performance of the application. - /// The enabledOptions controls which statistics are displayed. The bounds - /// controls where the statistics are displayed. - /// - /// enabledOptions is a bit field with the following bits defined: - /// - 0x01: displayRasterizerStatistics - show raster thread frame time - /// - 0x02: visualizeRasterizerStatistics - graph raster thread frame times - /// - 0x04: displayEngineStatistics - show UI thread frame time - /// - 0x08: visualizeEngineStatistics - graph UI thread frame times - /// Set enabledOptions to 0x0F to enable all the currently defined features. - /// - /// The "UI thread" is the thread that includes all the execution of - /// the main Dart isolate (the isolate that can call - /// [Window.render]). The UI thread frame time is the total time - /// spent executing the [Window.onBeginFrame] callback. The "raster - /// thread" is the thread (running on the CPU) that subsequently - /// processes the [Scene] provided by the Dart code to turn it into - /// GPU commands and send it to the GPU. - /// - /// See also the [PerformanceOverlayOption] enum in the rendering library. - /// for more details. void addPerformanceOverlay(int enabledOptions, Rect bounds); - - /// Adds a [Picture] to the scene. - /// - /// The picture is rasterized at the given offset. void addPicture( Offset offset, Picture picture, { bool isComplexHint = false, bool willChangeHint = false, }); - - /// Adds a backend texture to the scene. - /// - /// The texture is scaled to the given size and rasterized at the given - /// offset. void addTexture( int textureId, { Offset offset = Offset.zero, @@ -329,32 +112,12 @@ abstract class SceneBuilder { bool freeze = false, FilterQuality filterQuality = FilterQuality.low, }); - - /// Adds a platform view (e.g an iOS UIView) to the scene. - /// - /// Only supported on iOS, this is currently a no-op on other platforms. - /// - /// On iOS this layer splits the current output surface into two surfaces, one for the scene nodes - /// preceding the platform view, and one for the scene nodes following the platform view. - /// - /// ## Performance impact - /// - /// Adding an additional surface doubles the amount of graphics memory directly used by Flutter - /// for output buffers. Quartz might allocated extra buffers for compositing the Flutter surfaces - /// and the platform view. - /// - /// With a platform view in the scene, Quartz has to composite the two Flutter surfaces and the - /// embedded UIView. In addition to that, on iOS versions greater than 9, the Flutter frames are - /// synchronized with the UIView frames adding additional performance overhead. void addPlatformView( int viewId, { Offset offset = Offset.zero, double width = 0.0, double height = 0.0, }); - - /// (Fuchsia-only) Adds a scene rendered by another application to the scene - /// for this application. void addChildScene({ Offset offset = Offset.zero, double width = 0.0, @@ -362,52 +125,10 @@ abstract class SceneBuilder { required SceneHost sceneHost, bool hitTestable = true, }); - - /// Sets a threshold after which additional debugging information should be - /// recorded. - /// - /// Currently this interface is difficult to use by end-developers. If you're - /// interested in using this feature, please contact [flutter-dev](https://groups.google.com/forum/#!forum/flutter-dev). - /// We'll hopefully be able to figure out how to make this feature more useful - /// to you. void setRasterizerTracingThreshold(int frameInterval); - - /// Sets whether the raster cache should checkerboard cached entries. This is - /// only useful for debugging purposes. - /// - /// The compositor can sometimes decide to cache certain portions of the - /// widget hierarchy. Such portions typically don't change often from frame to - /// frame and are expensive to render. This can speed up overall rendering. - /// However, there is certain upfront cost to constructing these cache - /// entries. And, if the cache entries are not used very often, this cost may - /// not be worth the speedup in rendering of subsequent frames. If the - /// developer wants to be certain that populating the raster cache is not - /// causing stutters, this option can be set. Depending on the observations - /// made, hints can be provided to the compositor that aid it in making better - /// decisions about caching. - /// - /// Currently this interface is difficult to use by end-developers. If you're - /// interested in using this feature, please contact [flutter-dev](https://groups.google.com/forum/#!forum/flutter-dev). void setCheckerboardRasterCacheImages(bool checkerboard); - - /// Sets whether the compositor should checkerboard layers that are rendered - /// to offscreen bitmaps. - /// - /// This is only useful for debugging purposes. void setCheckerboardOffscreenLayers(bool checkerboard); - - /// Finishes building the scene. - /// - /// Returns a [Scene] containing the objects that have been added to - /// this scene builder. The [Scene] can then be displayed on the - /// screen with [Window.render]. - /// - /// After calling this function, the scene builder object is invalid and - /// cannot be used further. Scene build(); - - /// Set properties on the linked scene. These properties include its bounds, - /// as well as whether it can be the target of focus events or not. void setProperties( double width, double height, @@ -419,36 +140,16 @@ abstract class SceneBuilder { ); } -/// A handle for the framework to hold and retain an engine layer across frames. class EngineLayer {} -//// (Fuchsia-only) Hosts content provided by another application. class SceneHost { - /// Creates a host for a child scene's content. - /// - /// The ViewHolder token is bound to a ViewHolder scene graph node which acts - /// as a container for the child's content. The creator of the SceneHost is - /// responsible for sending the corresponding ViewToken to the child. - /// - /// The ViewHolder token is a dart:zircon Handle, but that type isn't - /// available here. This is called by ChildViewConnection in - /// //topaz/public/dart/fuchsia_scenic_flutter/. - /// - /// The SceneHost takes ownership of the provided ViewHolder token. SceneHost( dynamic viewHolderToken, void Function() viewConnectedCallback, void Function() viewDisconnectedCallback, void Function(bool) viewStateChangedCallback, ); - - /// Releases the resources associated with the SceneHost. - /// - /// After calling this function, the SceneHost cannot be used further. void dispose() {} - - /// Set properties on the linked scene. These properties include its bounds, - /// as well as whether it can be the target of focus events or not. void setProperties( double width, double height, diff --git a/engine/src/flutter/lib/web_ui/lib/src/ui/geometry.dart b/engine/src/flutter/lib/web_ui/lib/src/ui/geometry.dart index c528c8c73d..0ec3c06550 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/ui/geometry.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/ui/geometry.dart @@ -5,83 +5,19 @@ // @dart = 2.10 part of ui; -/// Base class for [Size] and [Offset], which are both ways to describe -/// a distance as a two-dimensional axis-aligned vector. abstract class OffsetBase { - /// Abstract const constructor. This constructor enables subclasses to provide - /// const constructors so that they can be used in const expressions. - /// - /// The first argument sets the horizontal component, and the second the - /// vertical component. const OffsetBase(this._dx, this._dy) : assert(_dx != null), // ignore: unnecessary_null_comparison assert(_dy != null); // ignore: unnecessary_null_comparison final double _dx; final double _dy; - - /// Returns true if either component is [double.infinity], and false if both - /// are finite (or negative infinity, or NaN). - /// - /// This is different than comparing for equality with an instance that has - /// _both_ components set to [double.infinity]. - /// - /// See also: - /// - /// * [isFinite], which is true if both components are finite (and not NaN). bool get isInfinite => _dx >= double.infinity || _dy >= double.infinity; - - /// Whether both components are finite (neither infinite nor NaN). - /// - /// See also: - /// - /// * [isInfinite], which returns true if either component is equal to - /// positive infinity. bool get isFinite => _dx.isFinite && _dy.isFinite; - - /// Less-than operator. Compares an [Offset] or [Size] to another [Offset] or - /// [Size], and returns true if both the horizontal and vertical values of the - /// left-hand-side operand are smaller than the horizontal and vertical values - /// of the right-hand-side operand respectively. Returns false otherwise. - /// - /// This is a partial ordering. It is possible for two values to be neither - /// less, nor greater than, nor equal to, another. bool operator <(OffsetBase other) => _dx < other._dx && _dy < other._dy; - - /// Less-than-or-equal-to operator. Compares an [Offset] or [Size] to another - /// [Offset] or [Size], and returns true if both the horizontal and vertical - /// values of the left-hand-side operand are smaller than or equal to the - /// horizontal and vertical values of the right-hand-side operand - /// respectively. Returns false otherwise. - /// - /// This is a partial ordering. It is possible for two values to be neither - /// less, nor greater than, nor equal to, another. bool operator <=(OffsetBase other) => _dx <= other._dx && _dy <= other._dy; - - /// Greater-than operator. Compares an [Offset] or [Size] to another [Offset] - /// or [Size], and returns true if both the horizontal and vertical values of - /// the left-hand-side operand are bigger than the horizontal and vertical - /// values of the right-hand-side operand respectively. Returns false - /// otherwise. - /// - /// This is a partial ordering. It is possible for two values to be neither - /// less, nor greater than, nor equal to, another. bool operator >(OffsetBase other) => _dx > other._dx && _dy > other._dy; - - /// Greater-than-or-equal-to operator. Compares an [Offset] or [Size] to - /// another [Offset] or [Size], and returns true if both the horizontal and - /// vertical values of the left-hand-side operand are bigger than or equal to - /// the horizontal and vertical values of the right-hand-side operand - /// respectively. Returns false otherwise. - /// - /// This is a partial ordering. It is possible for two values to be neither - /// less, nor greater than, nor equal to, another. bool operator >=(OffsetBase other) => _dx >= other._dx && _dy >= other._dy; - - /// Equality operator. Compares an [Offset] or [Size] to another [Offset] or - /// [Size], and returns true if the horizontal and vertical values of the - /// left-hand-side operand are equal to the horizontal and vertical values of - /// the right-hand-side operand respectively. Returns false otherwise. @override bool operator ==(Object other) { return other is OffsetBase @@ -96,224 +32,29 @@ abstract class OffsetBase { String toString() => 'OffsetBase(${_dx.toStringAsFixed(1)}, ${_dy.toStringAsFixed(1)})'; } -/// An immutable 2D floating-point offset. -/// -/// Generally speaking, Offsets can be interpreted in two ways: -/// -/// 1. As representing a point in Cartesian space a specified distance from a -/// separately-maintained origin. For example, the top-left position of -/// children in the [RenderBox] protocol is typically represented as an -/// [Offset] from the top left of the parent box. -/// -/// 2. As a vector that can be applied to coordinates. For example, when -/// painting a [RenderObject], the parent is passed an [Offset] from the -/// screen's origin which it can add to the offsets of its children to find -/// the [Offset] from the screen's origin to each of the children. -/// -/// Because a particular [Offset] can be interpreted as one sense at one time -/// then as the other sense at a later time, the same class is used for both -/// senses. -/// -/// See also: -/// -/// * [Size], which represents a vector describing the size of a rectangle. class Offset extends OffsetBase { - /// Creates an offset. The first argument sets [dx], the horizontal component, - /// and the second sets [dy], the vertical component. const Offset(double dx, double dy) : super(dx, dy); - - /// Creates an offset from its [direction] and [distance]. - /// - /// The direction is in radians clockwise from the positive x-axis. - /// - /// The distance can be omitted, to create a unit vector (distance = 1.0). factory Offset.fromDirection(double direction, [ double distance = 1.0 ]) { return Offset(distance * math.cos(direction), distance * math.sin(direction)); } - - /// The x component of the offset. - /// - /// The y component is given by [dy]. double get dx => _dx; - - /// The y component of the offset. - /// - /// The x component is given by [dx]. double get dy => _dy; - - /// The magnitude of the offset. - /// - /// If you need this value to compare it to another [Offset]'s distance, - /// consider using [distanceSquared] instead, since it is cheaper to compute. double get distance => math.sqrt(dx * dx + dy * dy); - - /// The square of the magnitude of the offset. - /// - /// This is cheaper than computing the [distance] itself. double get distanceSquared => dx * dx + dy * dy; - - /// The angle of this offset as radians clockwise from the positive x-axis, in - /// the range -[pi] to [pi], assuming positive values of the x-axis go to the - /// left and positive values of the y-axis go down. - /// - /// Zero means that [dy] is zero and [dx] is zero or positive. - /// - /// Values from zero to [pi]/2 indicate positive values of [dx] and [dy], the - /// bottom-right quadrant. - /// - /// Values from [pi]/2 to [pi] indicate negative values of [dx] and positive - /// values of [dy], the bottom-left quadrant. - /// - /// Values from zero to -[pi]/2 indicate positive values of [dx] and negative - /// values of [dy], the top-right quadrant. - /// - /// Values from -[pi]/2 to -[pi] indicate negative values of [dx] and [dy], - /// the top-left quadrant. - /// - /// When [dy] is zero and [dx] is negative, the [direction] is [pi]. - /// - /// When [dx] is zero, [direction] is [pi]/2 if [dy] is positive and -[pi]/2 - /// if [dy] is negative. - /// - /// See also: - /// - /// * [distance], to compute the magnitude of the vector. - /// * [Canvas.rotate], which uses the same convention for its angle. double get direction => math.atan2(dy, dx); - - /// An offset with zero magnitude. - /// - /// This can be used to represent the origin of a coordinate space. static const Offset zero = Offset(0.0, 0.0); - - /// An offset with infinite x and y components. - /// - /// See also: - /// - /// * [isInfinite], which checks whether either component is infinite. - /// * [isFinite], which checks whether both components are finite. // This is included for completeness, because [Size.infinite] exists. static const Offset infinite = Offset(double.infinity, double.infinity); - - /// Returns a new offset with the x component scaled by `scaleX` and the y - /// component scaled by `scaleY`. - /// - /// If the two scale arguments are the same, consider using the `*` operator - /// instead: - /// - /// ```dart - /// Offset a = const Offset(10.0, 10.0); - /// Offset b = a * 2.0; // same as: a.scale(2.0, 2.0) - /// ``` - /// - /// If the two arguments are -1, consider using the unary `-` operator - /// instead: - /// - /// ```dart - /// Offset a = const Offset(10.0, 10.0); - /// Offset b = -a; // same as: a.scale(-1.0, -1.0) - /// ``` Offset scale(double scaleX, double scaleY) => Offset(dx * scaleX, dy * scaleY); - - /// Returns a new offset with translateX added to the x component and - /// translateY added to the y component. - /// - /// If the arguments come from another [Offset], consider using the `+` or `-` - /// operators instead: - /// - /// ```dart - /// Offset a = const Offset(10.0, 10.0); - /// Offset b = const Offset(10.0, 10.0); - /// Offset c = a + b; // same as: a.translate(b.dx, b.dy) - /// Offset d = a - b; // same as: a.translate(-b.dx, -b.dy) - /// ``` Offset translate(double translateX, double translateY) => Offset(dx + translateX, dy + translateY); - - /// Unary negation operator. - /// - /// Returns an offset with the coordinates negated. - /// - /// If the [Offset] represents an arrow on a plane, this operator returns the - /// same arrow but pointing in the reverse direction. Offset operator -() => Offset(-dx, -dy); - - /// Binary subtraction operator. - /// - /// Returns an offset whose [dx] value is the left-hand-side operand's [dx] - /// minus the right-hand-side operand's [dx] and whose [dy] value is the - /// left-hand-side operand's [dy] minus the right-hand-side operand's [dy]. - /// - /// See also [translate]. Offset operator -(Offset other) => Offset(dx - other.dx, dy - other.dy); - - /// Binary addition operator. - /// - /// Returns an offset whose [dx] value is the sum of the [dx] values of the - /// two operands, and whose [dy] value is the sum of the [dy] values of the - /// two operands. - /// - /// See also [translate]. Offset operator +(Offset other) => Offset(dx + other.dx, dy + other.dy); - - /// Multiplication operator. - /// - /// Returns an offset whose coordinates are the coordinates of the - /// left-hand-side operand (an Offset) multiplied by the scalar - /// right-hand-side operand (a double). - /// - /// See also [scale]. Offset operator *(double operand) => Offset(dx * operand, dy * operand); - - /// Division operator. - /// - /// Returns an offset whose coordinates are the coordinates of the - /// left-hand-side operand (an Offset) divided by the scalar right-hand-side - /// operand (a double). - /// - /// See also [scale]. Offset operator /(double operand) => Offset(dx / operand, dy / operand); - - /// Integer (truncating) division operator. - /// - /// Returns an offset whose coordinates are the coordinates of the - /// left-hand-side operand (an Offset) divided by the scalar right-hand-side - /// operand (a double), rounded towards zero. Offset operator ~/(double operand) => Offset((dx ~/ operand).toDouble(), (dy ~/ operand).toDouble()); - - /// Modulo (remainder) operator. - /// - /// Returns an offset whose coordinates are the remainder of dividing the - /// coordinates of the left-hand-side operand (an Offset) by the scalar - /// right-hand-side operand (a double). Offset operator %(double operand) => Offset(dx % operand, dy % operand); - - /// Rectangle constructor operator. - /// - /// Combines an [Offset] and a [Size] to form a [Rect] whose top-left - /// coordinate is the point given by adding this offset, the left-hand-side - /// operand, to the origin, and whose size is the right-hand-side operand. - /// - /// ```dart - /// Rect myRect = Offset.zero & const Size(100.0, 100.0); - /// // same as: Rect.fromLTWH(0.0, 0.0, 100.0, 100.0) - /// ``` Rect operator &(Size other) => Rect.fromLTWH(dx, dy, other.width, other.height); - - /// Linearly interpolate between two offsets. - /// - /// If either offset is null, this function interpolates from [Offset.zero]. - /// - /// The `t` argument represents position on the timeline, with 0.0 meaning - /// that the interpolation has not started, returning `a` (or something - /// equivalent to `a`), 1.0 meaning that the interpolation has finished, - /// returning `b` (or something equivalent to `b`), and values in between - /// meaning that the interpolation is at the relevant point on the timeline - /// between `a` and `b`. The interpolation can be extrapolated beyond 0.0 and - /// 1.0, so negative values and values greater than 1.0 are valid (and can - /// easily be generated by curves such as [Curves.elasticInOut]). - /// - /// Values for `t` are usually obtained from an [Animation], such as - /// an [AnimationController]. static Offset? lerp(Offset? a, Offset? b, double t) { assert(t != null); // ignore: unnecessary_null_comparison if (b == null) { @@ -331,7 +72,6 @@ class Offset extends OffsetBase { } } - /// Compares two Offsets for equality. @override bool operator ==(Object other) { return other is Offset @@ -346,61 +86,16 @@ class Offset extends OffsetBase { String toString() => 'Offset(${dx.toStringAsFixed(1)}, ${dy.toStringAsFixed(1)})'; } -/// Holds a 2D floating-point size. -/// -/// You can think of this as an [Offset] from the origin. class Size extends OffsetBase { - /// Creates a [Size] with the given [width] and [height]. const Size(double width, double height) : super(width, height); - - /// Creates an instance of [Size] that has the same values as another. // Used by the rendering library's _DebugSize hack. Size.copy(Size source) : super(source.width, source.height); - - /// Creates a square [Size] whose [width] and [height] are the given dimension. - /// - /// See also: - /// - /// * [Size.fromRadius], which is more convenient when the available size - /// is the radius of a circle. const Size.square(double dimension) : super(dimension, dimension); - - /// Creates a [Size] with the given [width] and an infinite [height]. const Size.fromWidth(double width) : super(width, double.infinity); - - /// Creates a [Size] with the given [height] and an infinite [width]. const Size.fromHeight(double height) : super(double.infinity, height); - - /// Creates a square [Size] whose [width] and [height] are twice the given - /// dimension. - /// - /// This is a square that contains a circle with the given radius. - /// - /// See also: - /// - /// * [Size.square], which creates a square with the given dimension. const Size.fromRadius(double radius) : super(radius * 2.0, radius * 2.0); - - /// The horizontal extent of this size. double get width => _dx; - - /// The vertical extent of this size. double get height => _dy; - - /// The aspect ratio of this size. - /// - /// This returns the [width] divided by the [height]. - /// - /// If the [width] is zero, the result will be zero. If the [height] is zero - /// (and the [width] is not), the result will be [double.infinity] or - /// [double.negativeInfinity] as determined by the sign of [width]. - /// - /// See also: - /// - /// * [AspectRatio], a widget for giving a child widget a specific aspect - /// ratio. - /// * [FittedBox], a widget that (in most modes) attempts to maintain a - /// child widget's aspect ratio while changing its size. double get aspectRatio { if (height != 0.0) return width / height; @@ -411,38 +106,9 @@ class Size extends OffsetBase { return 0.0; } - /// An empty size, one with a zero width and a zero height. static const Size zero = Size(0.0, 0.0); - - /// A size whose [width] and [height] are infinite. - /// - /// See also: - /// - /// * [isInfinite], which checks whether either dimension is infinite. - /// * [isFinite], which checks whether both dimensions are finite. static const Size infinite = Size(double.infinity, double.infinity); - - /// Whether this size encloses a non-zero area. - /// - /// Negative areas are considered empty. bool get isEmpty => width <= 0.0 || height <= 0.0; - - /// Binary subtraction operator for [Size]. - /// - /// Subtracting a [Size] from a [Size] returns the [Offset] that describes how - /// much bigger the left-hand-side operand is than the right-hand-side - /// operand. Adding that resulting [Offset] to the [Size] that was the - /// right-hand-side operand would return a [Size] equal to the [Size] that was - /// the left-hand-side operand. (i.e. if `sizeA - sizeB -> offsetA`, then - /// `offsetA + sizeB -> sizeA`) - /// - /// Subtracting an [Offset] from a [Size] returns the [Size] that is smaller than - /// the [Size] operand by the difference given by the [Offset] operand. In other - /// words, the returned [Size] has a [width] consisting of the [width] of the - /// left-hand-side operand minus the [Offset.dx] dimension of the - /// right-hand-side operand, and a [height] consisting of the [height] of the - /// left-hand-side operand minus the [Offset.dy] dimension of the - /// right-hand-side operand. OffsetBase operator -(OffsetBase other) { if (other is Size) return Offset(width - other.width, height - other.height); @@ -451,140 +117,30 @@ class Size extends OffsetBase { throw ArgumentError(other); } - /// Binary addition operator for adding an [Offset] to a [Size]. - /// - /// Returns a [Size] whose [width] is the sum of the [width] of the - /// left-hand-side operand, a [Size], and the [Offset.dx] dimension of the - /// right-hand-side operand, an [Offset], and whose [height] is the sum of the - /// [height] of the left-hand-side operand and the [Offset.dy] dimension of - /// the right-hand-side operand. Size operator +(Offset other) => Size(width + other.dx, height + other.dy); - - /// Multiplication operator. - /// - /// Returns a [Size] whose dimensions are the dimensions of the left-hand-side - /// operand (a [Size]) multiplied by the scalar right-hand-side operand (a - /// [double]). Size operator *(double operand) => Size(width * operand, height * operand); - - /// Division operator. - /// - /// Returns a [Size] whose dimensions are the dimensions of the left-hand-side - /// operand (a [Size]) divided by the scalar right-hand-side operand (a - /// [double]). Size operator /(double operand) => Size(width / operand, height / operand); - - /// Integer (truncating) division operator. - /// - /// Returns a [Size] whose dimensions are the dimensions of the left-hand-side - /// operand (a [Size]) divided by the scalar right-hand-side operand (a - /// [double]), rounded towards zero. Size operator ~/(double operand) => Size((width ~/ operand).toDouble(), (height ~/ operand).toDouble()); - - /// Modulo (remainder) operator. - /// - /// Returns a [Size] whose dimensions are the remainder of dividing the - /// left-hand-side operand (a [Size]) by the scalar right-hand-side operand (a - /// [double]). Size operator %(double operand) => Size(width % operand, height % operand); - - /// The lesser of the magnitudes of the [width] and the [height]. double get shortestSide => math.min(width.abs(), height.abs()); - - /// The greater of the magnitudes of the [width] and the [height]. double get longestSide => math.max(width.abs(), height.abs()); // Convenience methods that do the equivalent of calling the similarly named // methods on a Rect constructed from the given origin and this size. - - /// The offset to the intersection of the top and left edges of the rectangle - /// described by the given [Offset] (which is interpreted as the top-left corner) - /// and this [Size]. - /// - /// See also [Rect.topLeft]. Offset topLeft(Offset origin) => origin; - - /// The offset to the center of the top edge of the rectangle described by the - /// given offset (which is interpreted as the top-left corner) and this size. - /// - /// See also [Rect.topCenter]. Offset topCenter(Offset origin) => Offset(origin.dx + width / 2.0, origin.dy); - - /// The offset to the intersection of the top and right edges of the rectangle - /// described by the given offset (which is interpreted as the top-left corner) - /// and this size. - /// - /// See also [Rect.topRight]. Offset topRight(Offset origin) => Offset(origin.dx + width, origin.dy); - - /// The offset to the center of the left edge of the rectangle described by the - /// given offset (which is interpreted as the top-left corner) and this size. - /// - /// See also [Rect.centerLeft]. Offset centerLeft(Offset origin) => Offset(origin.dx, origin.dy + height / 2.0); - - /// The offset to the point halfway between the left and right and the top and - /// bottom edges of the rectangle described by the given offset (which is - /// interpreted as the top-left corner) and this size. - /// - /// See also [Rect.center]. Offset center(Offset origin) => Offset(origin.dx + width / 2.0, origin.dy + height / 2.0); - - /// The offset to the center of the right edge of the rectangle described by the - /// given offset (which is interpreted as the top-left corner) and this size. - /// - /// See also [Rect.centerLeft]. Offset centerRight(Offset origin) => Offset(origin.dx + width, origin.dy + height / 2.0); - - /// The offset to the intersection of the bottom and left edges of the - /// rectangle described by the given offset (which is interpreted as the - /// top-left corner) and this size. - /// - /// See also [Rect.bottomLeft]. Offset bottomLeft(Offset origin) => Offset(origin.dx, origin.dy + height); - - /// The offset to the center of the bottom edge of the rectangle described by - /// the given offset (which is interpreted as the top-left corner) and this - /// size. - /// - /// See also [Rect.bottomLeft]. Offset bottomCenter(Offset origin) => Offset(origin.dx + width / 2.0, origin.dy + height); - - /// The offset to the intersection of the bottom and right edges of the - /// rectangle described by the given offset (which is interpreted as the - /// top-left corner) and this size. - /// - /// See also [Rect.bottomRight]. Offset bottomRight(Offset origin) => Offset(origin.dx + width, origin.dy + height); - - /// Whether the point specified by the given offset (which is assumed to be - /// relative to the top left of the size) lies between the left and right and - /// the top and bottom edges of a rectangle of this size. - /// - /// Rectangles include their top and left edges but exclude their bottom and - /// right edges. bool contains(Offset offset) { return offset.dx >= 0.0 && offset.dx < width && offset.dy >= 0.0 && offset.dy < height; } - /// A [Size] with the [width] and [height] swapped. Size get flipped => Size(height, width); - - /// Linearly interpolate between two sizes - /// - /// If either size is null, this function interpolates from [Size.zero]. - /// - /// The `t` argument represents position on the timeline, with 0.0 meaning - /// that the interpolation has not started, returning `a` (or something - /// equivalent to `a`), 1.0 meaning that the interpolation has finished, - /// returning `b` (or something equivalent to `b`), and values in between - /// meaning that the interpolation is at the relevant point on the timeline - /// between `a` and `b`. The interpolation can be extrapolated beyond 0.0 and - /// 1.0, so negative values and values greater than 1.0 are valid (and can - /// easily be generated by curves such as [Curves.elasticInOut]). - /// - /// Values for `t` are usually obtained from an [Animation], such as - /// an [AnimationController]. static Size? lerp(Size? a, Size? b, double t) { assert(t != null); // ignore: unnecessary_null_comparison if (b == null) { @@ -602,7 +158,6 @@ class Size extends OffsetBase { } } - /// Compares two Sizes for equality. // We don't compare the runtimeType because of _DebugSize in the framework. @override bool operator ==(Object other) { @@ -618,95 +173,51 @@ class Size extends OffsetBase { String toString() => 'Size(${width.toStringAsFixed(1)}, ${height.toStringAsFixed(1)})'; } -/// An immutable, 2D, axis-aligned, floating-point rectangle whose coordinates -/// are relative to a given origin. -/// -/// A Rect can be created with one its constructors or from an [Offset] and a -/// [Size] using the `&` operator: -/// -/// ```dart -/// Rect myRect = const Offset(1.0, 2.0) & const Size(3.0, 4.0); -/// ``` class Rect { - /// Construct a rectangle from its left, top, right, and bottom edges. const Rect.fromLTRB(this.left, this.top, this.right, this.bottom) : assert(left != null), // ignore: unnecessary_null_comparison assert(top != null), // ignore: unnecessary_null_comparison assert(right != null), // ignore: unnecessary_null_comparison assert(bottom != null); // ignore: unnecessary_null_comparison - /// Construct a rectangle from its left and top edges, its width, and its - /// height. - /// - /// To construct a [Rect] from an [Offset] and a [Size], you can use the - /// rectangle constructor operator `&`. See [Offset.&]. - const Rect.fromLTWH(double left, double top, double width, double height) : this.fromLTRB(left, top, left + width, top + height); + const Rect.fromLTWH(double left, double top, double width, double height) + : this.fromLTRB(left, top, left + width, top + height); - /// Construct a rectangle that bounds the given circle. - /// - /// The `center` argument is assumed to be an offset from the origin. - Rect.fromCircle({ required Offset center, required double radius }) : this.fromCenter( - center: center, - width: radius * 2, - height: radius * 2, - ); + Rect.fromCircle({ required Offset center, required double radius }) + : this.fromCenter( + center: center, + width: radius * 2, + height: radius * 2, + ); - /// Constructs a rectangle from its center point, width, and height. - /// - /// The `center` argument is assumed to be an offset from the origin. - Rect.fromCenter({ required Offset center, required double width, required double height }) : this.fromLTRB( - center.dx - width / 2, - center.dy - height / 2, - center.dx + width / 2, - center.dy + height / 2, - ); + Rect.fromCenter({ required Offset center, required double width, required double height }) + : this.fromLTRB( + center.dx - width / 2, + center.dy - height / 2, + center.dx + width / 2, + center.dy + height / 2, + ); - /// Construct the smallest rectangle that encloses the given offsets, treating - /// them as vectors from the origin. - Rect.fromPoints(Offset a, Offset b) : this.fromLTRB( - math.min(a.dx, b.dx), - math.min(a.dy, b.dy), - math.max(a.dx, b.dx), - math.max(a.dy, b.dy), - ); + Rect.fromPoints(Offset a, Offset b) + : this.fromLTRB( + math.min(a.dx, b.dx), + math.min(a.dy, b.dy), + math.max(a.dx, b.dx), + math.max(a.dy, b.dy), + ); - /// The offset of the left edge of this rectangle from the x axis. final double left; - - /// The offset of the top edge of this rectangle from the y axis. final double top; - - /// The offset of the right edge of this rectangle from the x axis. final double right; - - /// The offset of the bottom edge of this rectangle from the y axis. final double bottom; - - /// The distance between the left and right edges of this rectangle. double get width => right - left; - - /// The distance between the top and bottom edges of this rectangle. double get height => bottom - top; - - /// The distance between the upper-left corner and the lower-right corner of - /// this rectangle. Size get size => Size(width, height); - - /// Whether any of the dimensions are `NaN`. bool get hasNaN => left.isNaN || top.isNaN || right.isNaN || bottom.isNaN; - - /// A rectangle with left, top, right, and bottom edges all at zero. static const Rect zero = Rect.fromLTRB(0.0, 0.0, 0.0, 0.0); static const double _giantScalar = 1.0E+9; // matches kGiantRect from layer.h - - /// A rectangle that covers the entire coordinate space. - /// - /// This covers the space from -1e9,-1e9 to 1e9,1e9. - /// This is the space over which graphics operations are valid. static const Rect largest = Rect.fromLTRB(-_giantScalar, -_giantScalar, _giantScalar, _giantScalar); - - /// Whether any of the coordinates of this rectangle are equal to positive infinity. // included for consistency with Offset and Size bool get isInfinite { return left >= double.infinity @@ -715,63 +226,39 @@ class Rect { || bottom >= double.infinity; } - /// Whether all coordinates of this rectangle are finite. bool get isFinite => left.isFinite && top.isFinite && right.isFinite && bottom.isFinite; - - /// Whether this rectangle encloses a non-zero area. Negative areas are - /// considered empty. bool get isEmpty => left >= right || top >= bottom; - - /// Returns a new rectangle translated by the given offset. - /// - /// To translate a rectangle by separate x and y components rather than by an - /// [Offset], consider [translate]. Rect shift(Offset offset) { return Rect.fromLTRB(left + offset.dx, top + offset.dy, right + offset.dx, bottom + offset.dy); } - /// Returns a new rectangle with translateX added to the x components and - /// translateY added to the y components. - /// - /// To translate a rectangle by an [Offset] rather than by separate x and y - /// components, consider [shift]. Rect translate(double translateX, double translateY) { return Rect.fromLTRB(left + translateX, top + translateY, right + translateX, bottom + translateY); } - /// Returns a new rectangle with edges moved outwards by the given delta. Rect inflate(double delta) { return Rect.fromLTRB(left - delta, top - delta, right + delta, bottom + delta); } - /// Returns a new rectangle with edges moved inwards by the given delta. Rect deflate(double delta) => inflate(-delta); - - /// Returns a new rectangle that is the intersection of the given - /// rectangle and this rectangle. The two rectangles must overlap - /// for this to be meaningful. If the two rectangles do not overlap, - /// then the resulting Rect will have a negative width or height. Rect intersect(Rect other) { return Rect.fromLTRB( math.max(left, other.left), math.max(top, other.top), math.min(right, other.right), - math.min(bottom, other.bottom) + math.min(bottom, other.bottom), ); } - /// Returns a new rectangle which is the bounding box containing this - /// rectangle and the given rectangle. Rect expandToInclude(Rect other) { return Rect.fromLTRB( - math.min(left, other.left), - math.min(top, other.top), - math.max(right, other.right), - math.max(bottom, other.bottom), + math.min(left, other.left), + math.min(top, other.top), + math.max(right, other.right), + math.max(bottom, other.bottom), ); } - /// Whether `other` has a nonzero area of overlap with this rectangle. bool overlaps(Rect other) { if (right <= other.left || other.right <= left) return false; @@ -780,85 +267,21 @@ class Rect { return true; } - /// The lesser of the magnitudes of the [width] and the [height] of this - /// rectangle. double get shortestSide => math.min(width.abs(), height.abs()); - - /// The greater of the magnitudes of the [width] and the [height] of this - /// rectangle. double get longestSide => math.max(width.abs(), height.abs()); - - /// The offset to the intersection of the top and left edges of this rectangle. - /// - /// See also [Size.topLeft]. Offset get topLeft => Offset(left, top); - - /// The offset to the center of the top edge of this rectangle. - /// - /// See also [Size.topCenter]. Offset get topCenter => Offset(left + width / 2.0, top); - - /// The offset to the intersection of the top and right edges of this rectangle. - /// - /// See also [Size.topRight]. Offset get topRight => Offset(right, top); - - /// The offset to the center of the left edge of this rectangle. - /// - /// See also [Size.centerLeft]. Offset get centerLeft => Offset(left, top + height / 2.0); - - /// The offset to the point halfway between the left and right and the top and - /// bottom edges of this rectangle. - /// - /// See also [Size.center]. Offset get center => Offset(left + width / 2.0, top + height / 2.0); - - /// The offset to the center of the right edge of this rectangle. - /// - /// See also [Size.centerLeft]. Offset get centerRight => Offset(right, top + height / 2.0); - - /// The offset to the intersection of the bottom and left edges of this rectangle. - /// - /// See also [Size.bottomLeft]. Offset get bottomLeft => Offset(left, bottom); - - /// The offset to the center of the bottom edge of this rectangle. - /// - /// See also [Size.bottomLeft]. Offset get bottomCenter => Offset(left + width / 2.0, bottom); - - /// The offset to the intersection of the bottom and right edges of this rectangle. - /// - /// See also [Size.bottomRight]. Offset get bottomRight => Offset(right, bottom); - - /// Whether the point specified by the given offset (which is assumed to be - /// relative to the origin) lies between the left and right and the top and - /// bottom edges of this rectangle. - /// - /// Rectangles include their top and left edges but exclude their bottom and - /// right edges. bool contains(Offset offset) { return offset.dx >= left && offset.dx < right && offset.dy >= top && offset.dy < bottom; } - /// Linearly interpolate between two rectangles. - /// - /// If either rect is null, [Rect.zero] is used as a substitute. - /// - /// The `t` argument represents position on the timeline, with 0.0 meaning - /// that the interpolation has not started, returning `a` (or something - /// equivalent to `a`), 1.0 meaning that the interpolation has finished, - /// returning `b` (or something equivalent to `b`), and values in between - /// meaning that the interpolation is at the relevant point on the timeline - /// between `a` and `b`. The interpolation can be extrapolated beyond 0.0 and - /// 1.0, so negative values and values greater than 1.0 are valid (and can - /// easily be generated by curves such as [Curves.elasticInOut]). - /// - /// Values for `t` are usually obtained from an [Animation], such as - /// an [AnimationController]. static Rect? lerp(Rect? a, Rect? b, double t) { assert(t != null); // ignore: unnecessary_null_comparison if (b == null) { @@ -902,92 +325,19 @@ class Rect { String toString() => 'Rect.fromLTRB(${left.toStringAsFixed(1)}, ${top.toStringAsFixed(1)}, ${right.toStringAsFixed(1)}, ${bottom.toStringAsFixed(1)})'; } -/// A radius for either circular or elliptical shapes. class Radius { - /// Constructs a circular radius. [x] and [y] will have the same radius value. const Radius.circular(double radius) : this.elliptical(radius, radius); - - /// Constructs an elliptical radius with the given radii. const Radius.elliptical(this.x, this.y); - - /// The radius value on the horizontal axis. final double x; - - /// The radius value on the vertical axis. final double y; - - /// A radius with [x] and [y] values set to zero. - /// - /// You can use [Radius.zero] with [RRect] to have right-angle corners. static const Radius zero = Radius.circular(0.0); - - /// Unary negation operator. - /// - /// Returns a Radius with the distances negated. - /// - /// Radiuses with negative values aren't geometrically meaningful, but could - /// occur as part of expressions. For example, negating a radius of one pixel - /// and then adding the result to another radius is equivalent to subtracting - /// a radius of one pixel from the other. Radius operator -() => Radius.elliptical(-x, -y); - - /// Binary subtraction operator. - /// - /// Returns a radius whose [x] value is the left-hand-side operand's [x] - /// minus the right-hand-side operand's [x] and whose [y] value is the - /// left-hand-side operand's [y] minus the right-hand-side operand's [y]. Radius operator -(Radius other) => Radius.elliptical(x - other.x, y - other.y); - - /// Binary addition operator. - /// - /// Returns a radius whose [x] value is the sum of the [x] values of the - /// two operands, and whose [y] value is the sum of the [y] values of the - /// two operands. Radius operator +(Radius other) => Radius.elliptical(x + other.x, y + other.y); - - /// Multiplication operator. - /// - /// Returns a radius whose coordinates are the coordinates of the - /// left-hand-side operand (a radius) multiplied by the scalar - /// right-hand-side operand (a double). Radius operator *(double operand) => Radius.elliptical(x * operand, y * operand); - - /// Division operator. - /// - /// Returns a radius whose coordinates are the coordinates of the - /// left-hand-side operand (a radius) divided by the scalar right-hand-side - /// operand (a double). Radius operator /(double operand) => Radius.elliptical(x / operand, y / operand); - - /// Integer (truncating) division operator. - /// - /// Returns a radius whose coordinates are the coordinates of the - /// left-hand-side operand (a radius) divided by the scalar right-hand-side - /// operand (a double), rounded towards zero. Radius operator ~/(double operand) => Radius.elliptical((x ~/ operand).toDouble(), (y ~/ operand).toDouble()); - - /// Modulo (remainder) operator. - /// - /// Returns a radius whose coordinates are the remainder of dividing the - /// coordinates of the left-hand-side operand (a radius) by the scalar - /// right-hand-side operand (a double). Radius operator %(double operand) => Radius.elliptical(x % operand, y % operand); - - /// Linearly interpolate between two radii. - /// - /// If either is null, this function substitutes [Radius.zero] instead. - /// - /// The `t` argument represents position on the timeline, with 0.0 meaning - /// that the interpolation has not started, returning `a` (or something - /// equivalent to `a`), 1.0 meaning that the interpolation has finished, - /// returning `b` (or something equivalent to `b`), and values in between - /// meaning that the interpolation is at the relevant point on the timeline - /// between `a` and `b`. The interpolation can be extrapolated beyond 0.0 and - /// 1.0, so negative values and values greater than 1.0 are valid (and can - /// easily be generated by curves such as [Curves.elasticInOut]). - /// - /// Values for `t` are usually obtained from an [Animation], such as - /// an [AnimationController]. static Radius? lerp(Radius? a, Radius? b, double t) { assert(t != null); // ignore: unnecessary_null_comparison if (b == null) { @@ -1032,32 +382,37 @@ class Radius { } } -/// An immutable rounded rectangle with the custom radii for all four corners. class RRect { - /// Construct a rounded rectangle from its left, top, right, and bottom edges, - /// and the same radii along its horizontal axis and its vertical axis. - const RRect.fromLTRBXY(double left, double top, double right, double bottom, - double radiusX, double radiusY) : this._raw( - top: top, - left: left, - right: right, - bottom: bottom, - tlRadiusX: radiusX, - tlRadiusY: radiusY, - trRadiusX: radiusX, - trRadiusY: radiusY, - blRadiusX: radiusX, - blRadiusY: radiusY, - brRadiusX: radiusX, - brRadiusY: radiusY, - uniformRadii: radiusX == radiusY, - ); + const RRect.fromLTRBXY( + double left, + double top, + double right, + double bottom, + double radiusX, + double radiusY, + ) : this._raw( + top: top, + left: left, + right: right, + bottom: bottom, + tlRadiusX: radiusX, + tlRadiusY: radiusY, + trRadiusX: radiusX, + trRadiusY: radiusY, + blRadiusX: radiusX, + blRadiusY: radiusY, + brRadiusX: radiusX, + brRadiusY: radiusY, + uniformRadii: radiusX == radiusY, + ); - /// Construct a rounded rectangle from its left, top, right, and bottom edges, - /// and the same radius in each corner. - RRect.fromLTRBR(double left, double top, double right, double bottom, - Radius radius) - : this._raw( + RRect.fromLTRBR( + double left, + double top, + double right, + double bottom, + Radius radius, + ) : this._raw( top: top, left: left, right: right, @@ -1073,8 +428,6 @@ class RRect { uniformRadii: radius.x == radius.y, ); - /// Construct a rounded rectangle from its bounding box and the same radii - /// along its horizontal axis and its vertical axis. RRect.fromRectXY(Rect rect, double radiusX, double radiusY) : this._raw( top: rect.top, @@ -1092,8 +445,6 @@ class RRect { uniformRadii: radiusX == radiusY, ); - /// Construct a rounded rectangle from its bounding box and a radius that is - /// the same in each corner. RRect.fromRectAndRadius(Rect rect, Radius radius) : this._raw( top: rect.top, @@ -1111,10 +462,6 @@ class RRect { uniformRadii: radius.x == radius.y, ); - /// Construct a rounded rectangle from its left, top, right, and bottom edges, - /// and topLeft, topRight, bottomRight, and bottomLeft radii. - /// - /// The corner radii default to [Radius.zero], i.e. right-angled corners. RRect.fromLTRBAndCorners( double left, double top, @@ -1146,19 +493,13 @@ class RRect { topLeft.x == bottomRight.y, ); - /// Construct a rounded rectangle from its bounding box and and topLeft, - /// topRight, bottomRight, and bottomLeft radii. - /// - /// The corner radii default to [Radius.zero], i.e. right-angled corners RRect.fromRectAndCorners( - Rect rect, - { - Radius topLeft = Radius.zero, - Radius topRight = Radius.zero, - Radius bottomRight = Radius.zero, - Radius bottomLeft = Radius.zero - } - ) : this._raw( + Rect rect, { + Radius topLeft = Radius.zero, + Radius topRight = Radius.zero, + Radius bottomRight = Radius.zero, + Radius bottomLeft = Radius.zero, + }) : this._raw( top: rect.top, left: rect.left, right: rect.right, @@ -1208,62 +549,26 @@ class RRect { assert(blRadiusY != null), // ignore: unnecessary_null_comparison this.webOnlyUniformRadii = uniformRadii; - /// The offset of the left edge of this rectangle from the x axis. final double left; - - /// The offset of the top edge of this rectangle from the y axis. final double top; - - /// The offset of the right edge of this rectangle from the x axis. final double right; - - /// The offset of the bottom edge of this rectangle from the y axis. final double bottom; - - /// The top-left horizontal radius. final double tlRadiusX; - - /// The top-left vertical radius. final double tlRadiusY; - - /// The top-left [Radius]. Radius get tlRadius => Radius.elliptical(tlRadiusX, tlRadiusY); - - /// The top-right horizontal radius. final double trRadiusX; - - /// The top-right vertical radius. final double trRadiusY; - - /// The top-right [Radius]. Radius get trRadius => Radius.elliptical(trRadiusX, trRadiusY); - - /// The bottom-right horizontal radius. final double brRadiusX; - - /// The bottom-right vertical radius. final double brRadiusY; - - /// The bottom-right [Radius]. Radius get brRadius => Radius.elliptical(brRadiusX, brRadiusY); - - /// The bottom-left horizontal radius. final double blRadiusX; - - /// The bottom-left vertical radius. final double blRadiusY; - - /// If radii is equal for all corners. // webOnly final bool webOnlyUniformRadii; - - /// The bottom-left [Radius]. Radius get blRadius => Radius.elliptical(blRadiusX, blRadiusY); - - /// A rounded rectangle with all the values set to zero. static const RRect zero = RRect._raw(); - /// Returns a new [RRect] translated by the given offset. RRect shift(Offset offset) { return RRect._raw( left: left + offset.dx, @@ -1281,8 +586,6 @@ class RRect { ); } - /// Returns a new [RRect] with edges and radii moved outwards by the given - /// delta. RRect inflate(double delta) { return RRect._raw( left: left - delta, @@ -1300,22 +603,10 @@ class RRect { ); } - /// Returns a new [RRect] with edges and radii moved inwards by the given delta. RRect deflate(double delta) => inflate(-delta); - - /// The distance between the left and right edges of this rectangle. double get width => right - left; - - /// The distance between the top and bottom edges of this rectangle. double get height => bottom - top; - - /// The bounding box of this rounded rectangle (the rectangle with no rounded corners). Rect get outerRect => Rect.fromLTRB(left, top, right, bottom); - - /// The non-rounded rectangle that is constrained by the smaller of the two - /// diagonals, with each diagonal traveling through the middle of the curve - /// corners. The middle of a corner is the intersection of the curve with its - /// respective quadrant bisector. Rect get safeInnerRect { const double kInsetFactor = 0.29289321881; // 1-cos(pi/4) @@ -1332,12 +623,6 @@ class RRect { ); } - /// The rectangle that would be formed using the axis-aligned intersection of - /// the sides of the rectangle, i.e., the rectangle formed from the - /// inner-most centers of the ellipses that form the corners. This is the - /// intersection of the [wideMiddleRect] and the [tallMiddleRect]. If any of - /// the intersections are void, the resulting [Rect] will have negative width - /// or height. Rect get middleRect { final double leftRadius = math.max(blRadiusX, tlRadiusX); final double topRadius = math.max(tlRadiusY, trRadiusY); @@ -1351,10 +636,6 @@ class RRect { ); } - /// The biggest rectangle that is entirely inside the rounded rectangle and - /// has the full width of the rounded rectangle. If the rounded rectangle does - /// not have an axis-aligned intersection of its left and right side, the - /// resulting [Rect] will have negative width or height. Rect get wideMiddleRect { final double topRadius = math.max(tlRadiusY, trRadiusY); final double bottomRadius = math.max(brRadiusY, blRadiusY); @@ -1366,10 +647,6 @@ class RRect { ); } - /// The biggest rectangle that is entirely inside the rounded rectangle and - /// has the full height of the rounded rectangle. If the rounded rectangle - /// does not have an axis-aligned intersection of its top and bottom side, the - /// resulting [Rect] will have negative width or height. Rect get tallMiddleRect { final double leftRadius = math.max(blRadiusX, tlRadiusX); final double rightRadius = math.max(trRadiusX, brRadiusX); @@ -1381,23 +658,15 @@ class RRect { ); } - /// Whether this rounded rectangle encloses a non-zero area. - /// Negative areas are considered empty. bool get isEmpty => left >= right || top >= bottom; - - /// Whether all coordinates of this rounded rectangle are finite. bool get isFinite => left.isFinite && top.isFinite && right.isFinite && bottom.isFinite; - - /// Whether this rounded rectangle is a simple rectangle with zero - /// corner radii. bool get isRect { - return (tlRadiusX == 0.0 || tlRadiusY == 0.0) && - (trRadiusX == 0.0 || trRadiusY == 0.0) && - (blRadiusX == 0.0 || blRadiusY == 0.0) && - (brRadiusX == 0.0 || brRadiusY == 0.0); + return (tlRadiusX == 0.0 || tlRadiusY == 0.0) + && (trRadiusX == 0.0 || trRadiusY == 0.0) + && (blRadiusX == 0.0 || blRadiusY == 0.0) + && (brRadiusX == 0.0 || brRadiusY == 0.0); } - /// Whether this rounded rectangle has a side with no straight section. bool get isStadium { return tlRadius == trRadius && trRadius == brRadius @@ -1405,7 +674,6 @@ class RRect { && (width <= 2.0 * tlRadiusX || height <= 2.0 * tlRadiusY); } - /// Whether this rounded rectangle has no side with a straight section. bool get isEllipse { return tlRadius == trRadius && trRadius == brRadius @@ -1414,24 +682,12 @@ class RRect { && height <= 2.0 * tlRadiusY; } - /// Whether this rounded rectangle would draw as a circle. bool get isCircle => width == height && isEllipse; - - /// The lesser of the magnitudes of the [width] and the [height] of this - /// rounded rectangle. double get shortestSide => math.min(width.abs(), height.abs()); - - /// The greater of the magnitudes of the [width] and the [height] of this - /// rounded rectangle. double get longestSide => math.max(width.abs(), height.abs()); - - /// Whether any of the dimensions are `NaN`. bool get hasNaN => left.isNaN || top.isNaN || right.isNaN || bottom.isNaN || trRadiusX.isNaN || trRadiusY.isNaN || tlRadiusX.isNaN || tlRadiusY.isNaN || brRadiusX.isNaN || brRadiusY.isNaN || blRadiusX.isNaN || blRadiusY.isNaN; - - /// The offset to the point halfway between the left and right and the top and - /// bottom edges of this rectangle. Offset get center => Offset(left + width / 2.0, top + height / 2.0); // Returns the minimum between min and scale to which radius1 and radius2 @@ -1443,15 +699,6 @@ class RRect { return min; } - /// Scales all radii so that on each side their sum will not exceed the size - /// of the width/height. - /// - /// Skia already handles RRects with radii that are too large in this way. - /// Therefore, this method is only needed for RRect use cases that require - /// the appropriately scaled radii values. - /// - /// See the [Skia scaling implementation](https://github.com/google/skia/blob/master/src/core/SkRRect.cpp) - /// for more details. RRect scaleRadii() { double scale = 1.0; scale = _getMin(scale, blRadiusY, tlRadiusY, height); @@ -1492,13 +739,6 @@ class RRect { ); } - /// Whether the point specified by the given offset (which is assumed to be - /// relative to the origin) lies inside the rounded rectangle. - /// - /// This method may allocate (and cache) a copy of the object with normalized - /// radii the first time it is called on a particular [RRect] instance. When - /// using this method, prefer to reuse existing [RRect]s rather than - /// recreating the object each time. bool contains(Offset point) { if (point.dx < left || point.dx >= right || point.dy < top || point.dy >= bottom) return false; // outside bounding box @@ -1547,21 +787,6 @@ class RRect { return true; } - /// Linearly interpolate between two rounded rectangles. - /// - /// If either is null, this function substitutes [RRect.zero] instead. - /// - /// The `t` argument represents position on the timeline, with 0.0 meaning - /// that the interpolation has not started, returning `a` (or something - /// equivalent to `a`), 1.0 meaning that the interpolation has finished, - /// returning `b` (or something equivalent to `b`), and values in between - /// meaning that the interpolation is at the relevant point on the timeline - /// between `a` and `b`. The interpolation can be extrapolated beyond 0.0 and - /// 1.0, so negative values and values greater than 1.0 are valid (and can - /// easily be generated by curves such as [Curves.elasticInOut]). - /// - /// Values for `t` are usually obtained from an [Animation], such as - /// an [AnimationController]. static RRect? lerp(RRect? a, RRect? b, double t) { assert(t != null); // ignore: unnecessary_null_comparison if (b == null) { @@ -1667,37 +892,9 @@ class RRect { ')'; } } - -/// A transform consisting of a translation, a rotation, and a uniform scale. -/// -/// Used by [Canvas.drawAtlas]. This is a more efficient way to represent these -/// simple transformations than a full matrix. // Modeled after Skia's SkRSXform. + class RSTransform { - /// Creates an RSTransform. - /// - /// An [RSTransform] expresses the combination of a translation, a rotation - /// around a particular point, and a scale factor. - /// - /// The first argument, `scos`, is the cosine of the rotation, multiplied by - /// the scale factor. - /// - /// The second argument, `ssin`, is the sine of the rotation, multiplied by - /// that same scale factor. - /// - /// The third argument is the x coordinate of the translation, minus the - /// `scos` argument multiplied by the x-coordinate of the rotation point, plus - /// the `ssin` argument multiplied by the y-coordinate of the rotation point. - /// - /// The fourth argument is the y coordinate of the translation, minus the `ssin` - /// argument multiplied by the x-coordinate of the rotation point, minus the - /// `scos` argument multiplied by the y-coordinate of the rotation point. - /// - /// The [RSTransform.fromComponents] method may be a simpler way to - /// construct these values. However, if there is a way to factor out the - /// computations of the sine and cosine of the rotation so that they can be - /// reused over multiple calls to this constructor, it may be more efficient - /// to directly use this constructor instead. RSTransform(double scos, double ssin, double tx, double ty) { _value ..[0] = scos @@ -1705,33 +902,13 @@ class RSTransform { ..[2] = tx ..[3] = ty; } - - /// Creates an RSTransform from its individual components. - /// - /// The `rotation` parameter gives the rotation in radians. - /// - /// The `scale` parameter describes the uniform scale factor. - /// - /// The `anchorX` and `anchorY` parameters give the coordinate of the point - /// around which to rotate. - /// - /// The `translateX` and `translateY` parameters give the coordinate of the - /// offset by which to translate. - /// - /// This constructor computes the arguments of the [new RSTransform] - /// constructor and then defers to that constructor to actually create the - /// object. If many [RSTransform] objects are being created and there is a way - /// to factor out the computations of the sine and cosine of the rotation - /// (which are computed each time this constructor is called) and reuse them - /// over multiple [RSTransform] objects, it may be more efficient to directly - /// use the more direct [new RSTransform] constructor instead. factory RSTransform.fromComponents({ required double rotation, required double scale, required double anchorX, required double anchorY, required double translateX, - required double translateY + required double translateY, }) { final double scos = math.cos(rotation) * scale; final double ssin = math.sin(rotation) * scale; @@ -1741,20 +918,8 @@ class RSTransform { } final Float32List _value = Float32List(4); - - /// The cosine of the rotation multiplied by the scale factor. double get scos => _value[0]; - - /// The sine of the rotation multiplied by that same scale factor. double get ssin => _value[1]; - - /// The x coordinate of the translation, minus [scos] multiplied by the - /// x-coordinate of the rotation point, plus [ssin] multiplied by the - /// y-coordinate of the rotation point. double get tx => _value[2]; - - /// The y coordinate of the translation, minus [ssin] multiplied by the - /// x-coordinate of the rotation point, minus [scos] multiplied by the - /// y-coordinate of the rotation point. double get ty => _value[3]; } diff --git a/engine/src/flutter/lib/web_ui/lib/src/ui/hash_codes.dart b/engine/src/flutter/lib/web_ui/lib/src/ui/hash_codes.dart index e91fb1cc5f..58efa17c69 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/ui/hash_codes.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/ui/hash_codes.dart @@ -5,10 +5,13 @@ // @dart = 2.10 part of ui; -class _HashEnd { const _HashEnd(); } +class _HashEnd { + const _HashEnd(); +} + const _HashEnd _hashEnd = _HashEnd(); -/// Jenkins hash function, optimized for small integers. +// Jenkins hash function, optimized for small integers. // // Borrowed from the dart sdk: sdk/lib/math/jenkins_smi_hash.dart. class _Jenkins { @@ -28,28 +31,28 @@ class _Jenkins { } } -/// Combine up to twenty objects' hash codes into one value. -/// -/// If you only need to handle one object's hash code, then just refer to its -/// [Object.hashCode] getter directly. -/// -/// If you need to combine an arbitrary number of objects from a [List] or other -/// [Iterable], use [hashList]. The output of [hashList] can be used as one of -/// the arguments to this function. -/// -/// For example: -/// -/// ```dart -/// int hashCode => hashValues(foo, bar, hashList(quux), baz); -/// ``` int hashValues( - Object? arg01, Object? arg02, [ Object? arg03 = _hashEnd, - Object? arg04 = _hashEnd, Object? arg05 = _hashEnd, Object? arg06 = _hashEnd, - Object? arg07 = _hashEnd, Object? arg08 = _hashEnd, Object? arg09 = _hashEnd, - Object? arg10 = _hashEnd, Object? arg11 = _hashEnd, Object? arg12 = _hashEnd, - Object? arg13 = _hashEnd, Object? arg14 = _hashEnd, Object? arg15 = _hashEnd, - Object? arg16 = _hashEnd, Object? arg17 = _hashEnd, Object? arg18 = _hashEnd, - Object? arg19 = _hashEnd, Object? arg20 = _hashEnd ]) { + Object? arg01, + Object? arg02, [ + Object? arg03 = _hashEnd, + Object? arg04 = _hashEnd, + Object? arg05 = _hashEnd, + Object? arg06 = _hashEnd, + Object? arg07 = _hashEnd, + Object? arg08 = _hashEnd, + Object? arg09 = _hashEnd, + Object? arg10 = _hashEnd, + Object? arg11 = _hashEnd, + Object? arg12 = _hashEnd, + Object? arg13 = _hashEnd, + Object? arg14 = _hashEnd, + Object? arg15 = _hashEnd, + Object? arg16 = _hashEnd, + Object? arg17 = _hashEnd, + Object? arg18 = _hashEnd, + Object? arg19 = _hashEnd, + Object? arg20 = _hashEnd, +]) { int result = 0; result = _Jenkins.combine(result, arg01); result = _Jenkins.combine(result, arg02); @@ -111,9 +114,6 @@ int hashValues( return _Jenkins.finish(result); } -/// Combine the [Object.hashCode] values of an arbitrary number of objects from -/// an [Iterable] into one value. This function will return the same value if -/// given null as if given an empty list. int hashList(Iterable? arguments) { int result = 0; if (arguments != null) { diff --git a/engine/src/flutter/lib/web_ui/lib/src/ui/initialization.dart b/engine/src/flutter/lib/web_ui/lib/src/ui/initialization.dart index 6865da8121..a7b06b3586 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/ui/initialization.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/ui/initialization.dart @@ -5,7 +5,6 @@ // @dart = 2.10 part of ui; -/// Initializes the platform. Future webOnlyInitializePlatform({ engine.AssetManager? assetManager, }) { @@ -51,11 +50,6 @@ engine.FontCollection? _fontCollection; bool _webOnlyIsInitialized = false; bool get webOnlyIsInitialized => _webOnlyIsInitialized; - -/// Specifies that the platform should use the given [AssetManager] to load -/// assets. -/// -/// The given asset manager is used to initialize the font collection. Future webOnlySetAssetManager(engine.AssetManager assetManager) async { assert(assetManager != null, 'Cannot set assetManager to null'); // ignore: unnecessary_null_comparison if (assetManager == _assetManager) { @@ -71,7 +65,6 @@ Future webOnlySetAssetManager(engine.AssetManager assetManager) async { _fontCollection!.clear(); } - if (_assetManager != null) { if (engine.experimentalUseSkia) { await engine.skiaFontCollection.registerFonts(_assetManager!); @@ -85,29 +78,16 @@ Future webOnlySetAssetManager(engine.AssetManager assetManager) async { } } -/// Flag that shows whether the Flutter Testing Behavior is enabled. -/// -/// This flag can be used to decide if the code is running from a Flutter Test -/// such as a Widget test. -/// -/// For example in these tests we use a predictable-size font which makes widget -/// tests less flaky. -bool get debugEmulateFlutterTesterEnvironment => - _debugEmulateFlutterTesterEnvironment; +bool get debugEmulateFlutterTesterEnvironment => _debugEmulateFlutterTesterEnvironment; set debugEmulateFlutterTesterEnvironment(bool value) { _debugEmulateFlutterTesterEnvironment = value; if (_debugEmulateFlutterTesterEnvironment) { const Size logicalSize = Size(800.0, 600.0); - engine.window.webOnlyDebugPhysicalSizeOverride = - logicalSize * window.devicePixelRatio; + engine.window.webOnlyDebugPhysicalSizeOverride = logicalSize * window.devicePixelRatio; } } bool _debugEmulateFlutterTesterEnvironment = false; - -/// This class handles downloading assets over the network. engine.AssetManager get webOnlyAssetManager => _assetManager!; - -/// A collection of fonts that may be used by the platform. engine.FontCollection get webOnlyFontCollection => _fontCollection!; diff --git a/engine/src/flutter/lib/web_ui/lib/src/ui/lerp.dart b/engine/src/flutter/lib/web_ui/lib/src/ui/lerp.dart index 5cd4c8ac1a..8287cbd4ee 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/ui/lerp.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/ui/lerp.dart @@ -5,7 +5,6 @@ // @dart = 2.10 part of ui; -/// Linearly interpolate between two numbers. double? lerpDouble(num? a, num? b, double t) { if (a == null && b == null) { return null; @@ -23,7 +22,6 @@ double _lerpInt(int a, int b, double t) { return a + (b - a) * t; } -/// Same as [num.clamp] but specialized for [int]. int _clampInt(int value, int min, int max) { assert(min <= max); if (value < min) { diff --git a/engine/src/flutter/lib/web_ui/lib/src/ui/natives.dart b/engine/src/flutter/lib/web_ui/lib/src/ui/natives.dart index 4763db34e5..48bd8912ca 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/ui/natives.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/ui/natives.dart @@ -19,27 +19,12 @@ class _Logger { static void _printString(String? s) { print(s); } + static void _printDebugString(String? s) { html.window.console.error(s!); } } -/// Returns runtime Dart compilation trace as a UTF-8 encoded memory buffer. -/// -/// The buffer contains a list of symbols compiled by the Dart JIT at runtime up to the point -/// when this function was called. This list can be saved to a text file and passed to tools -/// such as `flutter build` or Dart `gen_snapshot` in order to precompile this code offline. -/// -/// The list has one symbol per line of the following format: `,,\n`. -/// Here are some examples: -/// -/// ``` -/// dart:core,Duration,get:inMilliseconds -/// package:flutter/src/widgets/binding.dart,::,runApp -/// file:///.../my_app.dart,::,main -/// ``` -/// -/// This function is only effective in debug and dynamic modes, and will throw in AOT mode. List saveCompilationTrace() { throw UnimplementedError(); } diff --git a/engine/src/flutter/lib/web_ui/lib/src/ui/painting.dart b/engine/src/flutter/lib/web_ui/lib/src/ui/painting.dart index 9f46e337df..06fc4f445a 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/ui/painting.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/ui/painting.dart @@ -7,17 +7,14 @@ part of ui; // ignore: unused_element, Used in Shader assert. bool _offsetIsValid(Offset offset) { - assert(offset != null, - 'Offset argument was null.'); // ignore: unnecessary_null_comparison - assert(!offset.dx.isNaN && !offset.dy.isNaN, - 'Offset argument contained a NaN value.'); + assert(offset != null, 'Offset argument was null.'); // ignore: unnecessary_null_comparison + assert(!offset.dx.isNaN && !offset.dy.isNaN, 'Offset argument contained a NaN value.'); return true; } // ignore: unused_element, Used in Shader assert. bool _matrix4IsValid(Float32List matrix4) { - assert(matrix4 != null, - 'Matrix4 argument was null.'); // ignore: unnecessary_null_comparison + assert(matrix4 != null, 'Matrix4 argument was null.'); // ignore: unnecessary_null_comparison assert(matrix4.length == 16, 'Matrix4 must have 16 entries.'); return true; } @@ -25,12 +22,10 @@ bool _matrix4IsValid(Float32List matrix4) { void _validateColorStops(List colors, List? colorStops) { if (colorStops == null) { if (colors.length != 2) - throw ArgumentError( - '"colors" must have length 2 if "colorStops" is omitted.'); + throw ArgumentError('"colors" must have length 2 if "colorStops" is omitted.'); } else { if (colors.length != colorStops.length) - throw ArgumentError( - '"colors" and "colorStops" arguments must have equal length.'); + throw ArgumentError('"colors" and "colorStops" arguments must have equal length.'); } } @@ -38,92 +33,43 @@ Color _scaleAlpha(Color a, double factor) { return a.withAlpha(_clampInt((a.alpha * factor).round(), 0, 255)); } -/// An immutable 32 bit color value in ARGB class Color { - /// Construct a color from the lower 32 bits of an int. - /// - /// Bits 24-31 are the alpha value. - /// Bits 16-23 are the red value. - /// Bits 8-15 are the green value. - /// Bits 0-7 are the blue value. const Color(int value) : this.value = value & 0xFFFFFFFF; - - /// Construct a color from the lower 8 bits of four integers. const Color.fromARGB(int a, int r, int g, int b) : value = (((a & 0xff) << 24) | ((r & 0xff) << 16) | ((g & 0xff) << 8) | ((b & 0xff) << 0)) & 0xFFFFFFFF; - - /// Create a color from red, green, blue, and opacity, similar to `rgba()` in CSS. - /// - /// * `r` is [red], from 0 to 255. - /// * `g` is [green], from 0 to 255. - /// * `b` is [blue], from 0 to 255. - /// * `opacity` is alpha channel of this color as a double, with 0.0 being - /// transparent and 1.0 being fully opaque. - /// - /// Out of range values are brought into range using modulo 255. - /// - /// See also [fromARGB], which takes the opacity as an integer value. const Color.fromRGBO(int r, int g, int b, double opacity) : value = ((((opacity * 0xff ~/ 1) & 0xff) << 24) | ((r & 0xff) << 16) | ((g & 0xff) << 8) | ((b & 0xff) << 0)) & 0xFFFFFFFF; - - /// A 32 bit value representing this color. - /// - /// Bits 24-31 are the alpha value. - /// Bits 16-23 are the red value. - /// Bits 8-15 are the green value. - /// Bits 0-7 are the blue value. final int value; - - /// The alpha channel of this color in an 8 bit value. int get alpha => (0xff000000 & value) >> 24; - - /// The alpha channel of this color as a double. double get opacity => alpha / 0xFF; - - /// The red channel of this color in an 8 bit value. int get red => (0x00ff0000 & value) >> 16; - - /// The green channel of this color in an 8 bit value. int get green => (0x0000ff00 & value) >> 8; - - /// The blue channel of this color in an 8 bit value. int get blue => (0x000000ff & value) >> 0; - - /// Returns a new color that matches this color with the alpha channel - /// replaced with a (which ranges from 0 to 255). Color withAlpha(int a) { return Color.fromARGB(a, red, green, blue); } - /// Returns a new color that matches this color with the alpha channel - /// replaced with the given opacity (which ranges from 0.0 to 1.0). Color withOpacity(double opacity) { assert(opacity >= 0.0 && opacity <= 1.0); return withAlpha((255.0 * opacity).round()); } - /// Returns a new color that matches this color with the red channel replaced - /// with r. Color withRed(int r) { return Color.fromARGB(alpha, r, green, blue); } - /// Returns a new color that matches this color with the green channel - /// replaced with g. Color withGreen(int g) { return Color.fromARGB(alpha, red, g, blue); } - /// Returns a new color that matches this color with the blue channel replaced - /// with b. Color withBlue(int b) { return Color.fromARGB(alpha, red, green, b); } @@ -136,12 +82,6 @@ class Color { return math.pow((component + 0.055) / 1.055, 2.4) as double; } - /// Returns a brightness value between 0 for darkest and 1 for lightest. - /// - /// Represents the relative luminance of the color. This value is - /// computationally expensive to calculate. - /// - /// See . double computeLuminance() { // See final double R = _linearizeColorComponent(red / 0xFF); @@ -150,28 +90,6 @@ class Color { return 0.2126 * R + 0.7152 * G + 0.0722 * B; } - /// Linearly interpolate between two colors. - /// - /// This is intended to be fast but as a result may be ugly. Consider - /// [HSVColor] or writing custom logic for interpolating colors. - /// - /// If either color is null, this function linearly interpolates from a - /// transparent instance of the other color. This is usually preferable to - /// interpolating from [material.Colors.transparent] (`const - /// Color(0x00000000)`), which is specifically transparent _black_. - /// - /// The `t` argument represents position on the timeline, with 0.0 meaning - /// that the interpolation has not started, returning `a` (or something - /// equivalent to `a`), 1.0 meaning that the interpolation has finished, - /// returning `b` (or something equivalent to `b`), and values in between - /// meaning that the interpolation is at the relevant point on the timeline - /// between `a` and `b`. The interpolation can be extrapolated beyond 0.0 and - /// 1.0, so negative values and values greater than 1.0 are valid (and can - /// easily be generated by curves such as [Curves.elasticInOut]). Each channel - /// will be clamped to the range 0 to 255. - /// - /// Values for `t` are usually obtained from an [Animation], such as - /// an [AnimationController]. static Color? lerp(Color? a, Color? b, double t) { assert(t != null); // ignore: unnecessary_null_comparison if (b == null) { @@ -194,14 +112,6 @@ class Color { } } - /// Combine the foreground color as a transparent color over top - /// of a background color, and return the resulting combined color. - /// - /// This uses standard alpha blending ("SRC over DST") rules to produce a - /// blended color from two colors. This can be used as a performance - /// enhancement when trying to avoid needless alpha blending compositing - /// operations for two things that are solid colors with the same shape, but - /// overlay each other: instead, just paint one with the combined color. static Color alphaBlend(Color foreground, Color background) { final int alpha = foreground.alpha; if (alpha == 0x00) { @@ -232,9 +142,6 @@ class Color { } } - /// Returns an alpha value representative of the provided [opacity] value. - /// - /// The [opacity] value may not be null. static int getAlphaFromOpacity(double opacity) { assert(opacity != null); // ignore: unnecessary_null_comparison return (opacity.clamp(0.0, 1.0) * 255).round(); @@ -260,836 +167,110 @@ class Color { } } -/// Styles to use for line endings. -/// -/// See [Paint.strokeCap]. enum StrokeCap { - /// Begin and end contours with a flat edge and no extension. butt, - - /// Begin and end contours with a semi-circle extension. round, - - /// Begin and end contours with a half square extension. This is - /// similar to extending each contour by half the stroke width (as - /// given by [Paint.strokeWidth]). square, } -/// Styles to use for line segment joins. -/// -/// This only affects line joins for polygons drawn by [Canvas.drawPath] and -/// rectangles, not points drawn as lines with [Canvas.drawPoints]. -/// -/// See also: -/// -/// * [Paint.strokeJoin] and [Paint.strokeMiterLimit] for how this value is -/// used. -/// * [StrokeCap] for the different kinds of line endings. // These enum values must be kept in sync with SkPaint::Join. enum StrokeJoin { - /// Joins between line segments form sharp corners. - /// - /// {@animation 300 300 https://flutter.github.io/assets-for-api-docs/assets/dart-ui/miter_4_join.mp4} - /// - /// The center of the line segment is colored in the diagram above to - /// highlight the join, but in normal usage the join is the same color as the - /// line. - /// - /// See also: - /// - /// * [Paint.strokeJoin], used to set the line segment join style to this - /// value. - /// * [Paint.strokeMiterLimit], used to define when a miter is drawn instead - /// of a bevel when the join is set to this value. miter, - - /// Joins between line segments are semi-circular. - /// - /// {@animation 300 300 https://flutter.github.io/assets-for-api-docs/assets/dart-ui/round_join.mp4} - /// - /// The center of the line segment is colored in the diagram above to - /// highlight the join, but in normal usage the join is the same color as the - /// line. - /// - /// See also: - /// - /// * [Paint.strokeJoin], used to set the line segment join style to this - /// value. round, - - /// Joins between line segments connect the corners of the butt ends of the - /// line segments to give a beveled appearance. - /// - /// {@animation 300 300 https://flutter.github.io/assets-for-api-docs/assets/dart-ui/bevel_join.mp4} - /// - /// The center of the line segment is colored in the diagram above to - /// highlight the join, but in normal usage the join is the same color as the - /// line. - /// - /// See also: - /// - /// * [Paint.strokeJoin], used to set the line segment join style to this - /// value. bevel, } -/// Strategies for painting shapes and paths on a canvas. -/// -/// See [Paint.style]. enum PaintingStyle { - /// Apply the [Paint] to the inside of the shape. For example, when - /// applied to the [Paint.drawCircle] call, this results in a disc - /// of the given size being painted. fill, - - /// Apply the [Paint] to the edge of the shape. For example, when - /// applied to the [Paint.drawCircle] call, this results is a hoop - /// of the given size being painted. The line drawn on the edge will - /// be the width given by the [Paint.strokeWidth] property. stroke, } -/// Algorithms to use when painting on the canvas. -/// -/// When drawing a shape or image onto a canvas, different algorithms can be -/// used to blend the pixels. The different values of [BlendMode] specify -/// different such algorithms. -/// -/// Each algorithm has two inputs, the _source_, which is the image being drawn, -/// and the _destination_, which is the image into which the source image is -/// being composited. The destination is often thought of as the _background_. -/// The source and destination both have four color channels, the red, green, -/// blue, and alpha channels. These are typically represented as numbers in the -/// range 0.0 to 1.0. The output of the algorithm also has these same four -/// channels, with values computed from the source and destination. -/// -/// The documentation of each value below describes how the algorithm works. In -/// each case, an image shows the output of blending a source image with a -/// destination image. In the images below, the destination is represented by an -/// image with horizontal lines and an opaque landscape photograph, and the -/// source is represented by an image with vertical lines (the same lines but -/// rotated) and a bird clip-art image. The [src] mode shows only the source -/// image, and the [dst] mode shows only the destination image. In the -/// documentation below, the transparency is illustrated by a checkerboard -/// pattern. The [clear] mode drops both the source and destination, resulting -/// in an output that is entirely transparent (illustrated by a solid -/// checkerboard pattern). -/// -/// The horizontal and vertical bars in these images show the red, green, and -/// blue channels with varying opacity levels, then all three color channels -/// together with those same varying opacity levels, then all three color -/// channels set to zero with those varying opacity levels, then two bars -/// showing a red/green/blue repeating gradient, the first with full opacity and -/// the second with partial opacity, and finally a bar with the three color -/// channels set to zero but the opacity varying in a repeating gradient. -/// -/// ## Application to the [Canvas] API -/// -/// When using [Canvas.saveLayer] and [Canvas.restore], the blend mode of the -/// [Paint] given to the [Canvas.saveLayer] will be applied when -/// [Canvas.restore] is called. Each call to [Canvas.saveLayer] introduces a new -/// layer onto which shapes and images are painted; when [Canvas.restore] is -/// called, that layer is then composited onto the parent layer, with the source -/// being the most-recently-drawn shapes and images, and the destination being -/// the parent layer. (For the first [Canvas.saveLayer] call, the parent layer -/// is the canvas itself.) -/// -/// See also: -/// -/// * [Paint.blendMode], which uses [BlendMode] to define the compositing -/// strategy. enum BlendMode { // This list comes from Skia's SkXfermode.h and the values (order) should be // kept in sync. // See: https://skia.org/user/api/skpaint#SkXfermode - - /// Drop both the source and destination images, leaving nothing. - /// - /// This corresponds to the "clear" Porter-Duff operator. - /// - /// ![](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/blend_mode_clear.png) clear, - - /// Drop the destination image, only paint the source image. - /// - /// Conceptually, the destination is first cleared, then the source image is - /// painted. - /// - /// This corresponds to the "Copy" Porter-Duff operator. - /// - /// ![](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/blend_mode_src.png) src, - - /// Drop the source image, only paint the destination image. - /// - /// Conceptually, the source image is discarded, leaving the destination - /// untouched. - /// - /// This corresponds to the "Destination" Porter-Duff operator. - /// - /// ![](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/blend_mode_dst.png) dst, - - /// Composite the source image over the destination image. - /// - /// This is the default value. It represents the most intuitive case, where - /// shapes are painted on top of what is below, with transparent areas showing - /// the destination layer. - /// - /// This corresponds to the "Source over Destination" Porter-Duff operator, - /// also known as the Painter's Algorithm. - /// - /// ![](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/blend_mode_srcOver.png) srcOver, - - /// Composite the source image under the destination image. - /// - /// This is the opposite of [srcOver]. - /// - /// This corresponds to the "Destination over Source" Porter-Duff operator. - /// - /// ![](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/blend_mode_dstOver.png) - /// - /// This is useful when the source image should have been painted before the - /// destination image, but could not be. dstOver, - - /// Show the source image, but only where the two images overlap. The - /// destination image is not rendered, it is treated merely as a mask. The - /// color channels of the destination are ignored, only the opacity has an - /// effect. - /// - /// To show the destination image instead, consider [dstIn]. - /// - /// To reverse the semantic of the mask (only showing the source where the - /// destination is absent, rather than where it is present), consider - /// [srcOut]. - /// - /// This corresponds to the "Source in Destination" Porter-Duff operator. - /// - /// ![](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/blend_mode_srcIn.png) srcIn, - - /// Show the destination image, but only where the two images overlap. The - /// source image is not rendered, it is treated merely as a mask. The color - /// channels of the source are ignored, only the opacity has an effect. - /// - /// To show the source image instead, consider [srcIn]. - /// - /// To reverse the semantic of the mask (only showing the source where the - /// destination is present, rather than where it is absent), consider - /// [dstOut]. - /// - /// This corresponds to the "Destination in Source" Porter-Duff operator. - /// - /// ![](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/blend_mode_dstIn.png) dstIn, - - /// Show the source image, but only where the two images do not overlap. The - /// destination image is not rendered, it is treated merely as a mask. The color - /// channels of the destination are ignored, only the opacity has an effect. - /// - /// To show the destination image instead, consider [dstOut]. - /// - /// To reverse the semantic of the mask (only showing the source where the - /// destination is present, rather than where it is absent), consider [srcIn]. - /// - /// This corresponds to the "Source out Destination" Porter-Duff operator. - /// - /// ![](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/blend_mode_srcOut.png) srcOut, - - /// Show the destination image, but only where the two images do not overlap. - /// The source image is not rendered, it is treated merely as a mask. The - /// color channels of the source are ignored, only the opacity has an effect. - /// - /// To show the source image instead, consider [srcOut]. - /// - /// To reverse the semantic of the mask (only showing the destination where - /// the source is present, rather than where it is absent), consider [dstIn]. - /// - /// This corresponds to the "Destination out Source" Porter-Duff operator. - /// - /// ![](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/blend_mode_dstOut.png) dstOut, - - /// Composite the source image over the destination image, but only where it - /// overlaps the destination. - /// - /// This corresponds to the "Source atop Destination" Porter-Duff operator. - /// - /// This is essentially the [srcOver] operator, but with the output's opacity - /// channel being set to that of the destination image instead of being a - /// combination of both image's opacity channels. - /// - /// For a variant with the destination on top instead of the source, see - /// [dstATop]. - /// - /// ![](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/blend_mode_srcATop.png) srcATop, - - /// Composite the destination image over the source image, but only where it - /// overlaps the source. - /// - /// This corresponds to the "Destination atop Source" Porter-Duff operator. - /// - /// This is essentially the [dstOver] operator, but with the output's opacity - /// channel being set to that of the source image instead of being a - /// combination of both image's opacity channels. - /// - /// For a variant with the source on top instead of the destination, see - /// [srcATop]. - /// - /// ![](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/blend_mode_dstATop.png) dstATop, - - /// Apply a bitwise `xor` operator to the source and destination images. This - /// leaves transparency where they would overlap. - /// - /// This corresponds to the "Source xor Destination" Porter-Duff operator. - /// - /// ![](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/blend_mode_xor.png) xor, - - /// Sum the components of the source and destination images. - /// - /// Transparency in a pixel of one of the images reduces the contribution of - /// that image to the corresponding output pixel, as if the color of that - /// pixel in that image was darker. - /// - /// This corresponds to the "Source plus Destination" Porter-Duff operator. - /// - /// ![](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/blend_mode_plus.png) plus, - - /// Multiply the color components of the source and destination images. - /// - /// This can only result in the same or darker colors (multiplying by white, - /// 1.0, results in no change; multiplying by black, 0.0, results in black). - /// - /// When compositing two opaque images, this has similar effect to overlapping - /// two transparencies on a projector. - /// - /// For a variant that also multiplies the alpha channel, consider [multiply]. - /// - /// ![](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/blend_mode_modulate.png) - /// - /// See also: - /// - /// * [screen], which does a similar computation but inverted. - /// * [overlay], which combines [modulate] and [screen] to favor the - /// destination image. - /// * [hardLight], which combines [modulate] and [screen] to favor the - /// source image. modulate, // Following blend modes are defined in the CSS Compositing standard. - - /// Multiply the inverse of the components of the source and destination - /// images, and inverse the result. - /// - /// Inverting the components means that a fully saturated channel (opaque - /// white) is treated as the value 0.0, and values normally treated as 0.0 - /// (black, transparent) are treated as 1.0. - /// - /// This is essentially the same as [modulate] blend mode, but with the values - /// of the colors inverted before the multiplication and the result being - /// inverted back before rendering. - /// - /// This can only result in the same or lighter colors (multiplying by black, - /// 1.0, results in no change; multiplying by white, 0.0, results in white). - /// Similarly, in the alpha channel, it can only result in more opaque colors. - /// - /// This has similar effect to two projectors displaying their images on the - /// same screen simultaneously. - /// - /// ![](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/blend_mode_screen.png) - /// - /// See also: - /// - /// * [modulate], which does a similar computation but without inverting the - /// values. - /// * [overlay], which combines [modulate] and [screen] to favor the - /// destination image. - /// * [hardLight], which combines [modulate] and [screen] to favor the - /// source image. screen, // The last coeff mode. - - /// Multiply the components of the source and destination images after - /// adjusting them to favor the destination. - /// - /// Specifically, if the destination value is smaller, this multiplies it with - /// the source value, whereas is the source value is smaller, it multiplies - /// the inverse of the source value with the inverse of the destination value, - /// then inverts the result. - /// - /// Inverting the components means that a fully saturated channel (opaque - /// white) is treated as the value 0.0, and values normally treated as 0.0 - /// (black, transparent) are treated as 1.0. - /// - /// ![](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/blend_mode_overlay.png) - /// - /// See also: - /// - /// * [modulate], which always multiplies the values. - /// * [screen], which always multiplies the inverses of the values. - /// * [hardLight], which is similar to [overlay] but favors the source image - /// instead of the destination image. overlay, - - /// Composite the source and destination image by choosing the lowest value - /// from each color channel. - /// - /// The opacity of the output image is computed in the same way as for - /// [srcOver]. - /// - /// ![](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/blend_mode_darken.png) darken, - - /// Composite the source and destination image by choosing the highest value - /// from each color channel. - /// - /// The opacity of the output image is computed in the same way as for - /// [srcOver]. - /// - /// ![](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/blend_mode_lighten.png) lighten, - - /// Divide the destination by the inverse of the source. - /// - /// Inverting the components means that a fully saturated channel (opaque - /// white) is treated as the value 0.0, and values normally treated as 0.0 - /// (black, transparent) are treated as 1.0. - /// - /// ![](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/blend_mode_colorDodge.png) colorDodge, - - /// Divide the inverse of the destination by the source, and inverse the result. - /// - /// Inverting the components means that a fully saturated channel (opaque - /// white) is treated as the value 0.0, and values normally treated as 0.0 - /// (black, transparent) are treated as 1.0. - /// - /// ![](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/blend_mode_colorBurn.png) colorBurn, - - /// Multiply the components of the source and destination images after - /// adjusting them to favor the source. - /// - /// Specifically, if the source value is smaller, this multiplies it with the - /// destination value, whereas is the destination value is smaller, it - /// multiplies the inverse of the destination value with the inverse of the - /// source value, then inverts the result. - /// - /// Inverting the components means that a fully saturated channel (opaque - /// white) is treated as the value 0.0, and values normally treated as 0.0 - /// (black, transparent) are treated as 1.0. - /// - /// ![](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/blend_mode_hardLight.png) - /// - /// See also: - /// - /// * [modulate], which always multiplies the values. - /// * [screen], which always multiplies the inverses of the values. - /// * [overlay], which is similar to [hardLight] but favors the destination - /// image instead of the source image. hardLight, - - /// Use [colorDodge] for source values below 0.5 and [colorBurn] for source - /// values above 0.5. - /// - /// This results in a similar but softer effect than [overlay]. - /// - /// ![](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/blend_mode_softLight.png) - /// - /// See also: - /// - /// * [color], which is a more subtle tinting effect. softLight, - - /// Subtract the smaller value from the bigger value for each channel. - /// - /// Compositing black has no effect; compositing white inverts the colors of - /// the other image. - /// - /// The opacity of the output image is computed in the same way as for - /// [srcOver]. - /// - /// The effect is similar to [exclusion] but harsher. - /// - /// ![](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/blend_mode_difference.png) difference, - - /// Subtract double the product of the two images from the sum of the two - /// images. - /// - /// Compositing black has no effect; compositing white inverts the colors of - /// the other image. - /// - /// The opacity of the output image is computed in the same way as for - /// [srcOver]. - /// - /// The effect is similar to [difference] but softer. - /// - /// ![](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/blend_mode_exclusion.png) exclusion, - - /// Multiply the components of the source and destination images, including - /// the alpha channel. - /// - /// This can only result in the same or darker colors (multiplying by white, - /// 1.0, results in no change; multiplying by black, 0.0, results in black). - /// - /// Since the alpha channel is also multiplied, a fully-transparent pixel - /// (opacity 0.0) in one image results in a fully transparent pixel in the - /// output. This is similar to [dstIn], but with the colors combined. - /// - /// For a variant that multiplies the colors but does not multiply the alpha - /// channel, consider [modulate]. - /// - /// ![](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/blend_mode_multiply.png) multiply, // The last separable mode. - - /// Take the hue of the source image, and the saturation and luminosity of the - /// destination image. - /// - /// The effect is to tint the destination image with the source image. - /// - /// The opacity of the output image is computed in the same way as for - /// [srcOver]. Regions that are entirely transparent in the source image take - /// their hue from the destination. - /// - /// ![](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/blend_mode_hue.png) - /// - /// See also: - /// - /// * [color], which is a similar but stronger effect as it also applies the - /// saturation of the source image. - /// * [HSVColor], which allows colors to be expressed using Hue rather than - /// the red/green/blue channels of [Color]. hue, - - /// Take the saturation of the source image, and the hue and luminosity of the - /// destination image. - /// - /// The opacity of the output image is computed in the same way as for - /// [srcOver]. Regions that are entirely transparent in the source image take - /// their saturation from the destination. - /// - /// ![](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/blend_mode_hue.png) - /// - /// See also: - /// - /// * [color], which also applies the hue of the source image. - /// * [luminosity], which applies the luminosity of the source image to the - /// destination. saturation, - - /// Take the hue and saturation of the source image, and the luminosity of the - /// destination image. - /// - /// The effect is to tint the destination image with the source image. - /// - /// The opacity of the output image is computed in the same way as for - /// [srcOver]. Regions that are entirely transparent in the source image take - /// their hue and saturation from the destination. - /// - /// ![](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/blend_mode_color.png) - /// - /// See also: - /// - /// * [hue], which is a similar but weaker effect. - /// * [softLight], which is a similar tinting effect but also tints white. - /// * [saturation], which only applies the saturation of the source image. color, - - /// Take the luminosity of the source image, and the hue and saturation of the - /// destination image. - /// - /// The opacity of the output image is computed in the same way as for - /// [srcOver]. Regions that are entirely transparent in the source image take - /// their luminosity from the destination. - /// - /// ![](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/blend_mode_luminosity.png) - /// - /// See also: - /// - /// * [saturation], which applies the saturation of the source image to the - /// destination. - /// * [ImageFilter.blur], which can be used with [BackdropFilter] for a - /// related effect. luminosity, } -/// Different ways to clip a widget's content. enum Clip { - /// No clip at all. - /// - /// This is the default option for most widgets: if the content does not - /// overflow the widget boundary, don't pay any performance cost for clipping. - /// - /// If the content does overflow, please explicitly specify the following - /// [Clip] options: - /// * [hardEdge], which is the fastest clipping, but with lower fidelity. - /// * [antiAlias], which is a little slower than [hardEdge], but with smoothed edges. - /// * [antiAliasWithSaveLayer], which is much slower than [antiAlias], and should - /// rarely be used. none, - - /// Clip, but do not apply anti-aliasing. - /// - /// This mode enables clipping, but curves and non-axis-aligned straight lines will be - /// jagged as no effort is made to anti-alias. - /// - /// Faster than other clipping modes, but slower than [none]. - /// - /// This is a reasonable choice when clipping is needed, if the container is an axis- - /// aligned rectangle or an axis-aligned rounded rectangle with very small corner radii. - /// - /// See also: - /// - /// * [antiAlias], which is more reasonable when clipping is needed and the shape is not - /// an axis-aligned rectangle. hardEdge, - - /// Clip with anti-aliasing. - /// - /// This mode has anti-aliased clipping edges to achieve a smoother look. - /// - /// It' s much faster than [antiAliasWithSaveLayer], but slower than [hardEdge]. - /// - /// This will be the common case when dealing with circles and arcs. - /// - /// Different from [hardEdge] and [antiAliasWithSaveLayer], this clipping may have - /// bleeding edge artifacts. - /// (See https://fiddle.skia.org/c/21cb4c2b2515996b537f36e7819288ae for an example.) - /// - /// See also: - /// - /// * [hardEdge], which is a little faster, but with lower fidelity. - /// * [antiAliasWithSaveLayer], which is much slower, but can avoid the - /// bleeding edges if there's no other way. - /// * [Paint.isAntiAlias], which is the anti-aliasing switch for general draw operations. antiAlias, - - /// Clip with anti-aliasing and saveLayer immediately following the clip. - /// - /// This mode not only clips with anti-aliasing, but also allocates an offscreen - /// buffer. All subsequent paints are carried out on that buffer before finally - /// being clipped and composited back. - /// - /// This is very slow. It has no bleeding edge artifacts (that [antiAlias] has) - /// but it changes the semantics as an offscreen buffer is now introduced. - /// (See https://github.com/flutter/flutter/issues/18057#issuecomment-394197336 - /// for a difference between paint without saveLayer and paint with saveLayer.) - /// - /// This will be only rarely needed. One case where you might need this is if - /// you have an image overlaid on a very different background color. In these - /// cases, consider whether you can avoid overlaying multiple colors in one - /// spot (e.g. by having the background color only present where the image is - /// absent). If you can, [antiAlias] would be fine and much faster. - /// - /// See also: - /// - /// * [antiAlias], which is much faster, and has similar clipping results. antiAliasWithSaveLayer, } -/// A description of the style to use when drawing on a [Canvas]. -/// -/// Most APIs on [Canvas] take a [Paint] object to describe the style -/// to use for that operation. abstract class Paint { - /// Constructs an empty [Paint] object with all fields initialized to - /// their defaults. - factory Paint() => - engine.experimentalUseSkia ? engine.CkPaint() : engine.SurfacePaint(); - - /// Whether to dither the output when drawing images. - /// - /// If false, the default value, dithering will be enabled when the input - /// color depth is higher than the output color depth. For example, - /// drawing an RGB8 image onto an RGB565 canvas. - /// - /// This value also controls dithering of [shader]s, which can make - /// gradients appear smoother. - /// - /// Whether or not dithering affects the output is implementation defined. - /// Some implementations may choose to ignore this completely, if they're - /// unable to control dithering. - /// - /// To ensure that dithering is consistently enabled for your entire - /// application, set this to true before invoking any drawing related code. + factory Paint() => engine.experimentalUseSkia ? engine.CkPaint() : engine.SurfacePaint(); static bool enableDithering = false; - - /// A blend mode to apply when a shape is drawn or a layer is composited. - /// - /// The source colors are from the shape being drawn (e.g. from - /// [Canvas.drawPath]) or layer being composited (the graphics that were drawn - /// between the [Canvas.saveLayer] and [Canvas.restore] calls), after applying - /// the [colorFilter], if any. - /// - /// The destination colors are from the background onto which the shape or - /// layer is being composited. - /// - /// Defaults to [BlendMode.srcOver]. - /// - /// See also: - /// - /// * [Canvas.saveLayer], which uses its [Paint]'s [blendMode] to composite - /// the layer when [restore] is called. - /// * [BlendMode], which discusses the user of [saveLayer] with [blendMode]. BlendMode get blendMode; set blendMode(BlendMode value); - - /// Whether to paint inside shapes, the edges of shapes, or both. - /// - /// If null, defaults to [PaintingStyle.fill]. PaintingStyle get style; set style(PaintingStyle value); - - /// How wide to make edges drawn when [style] is set to - /// [PaintingStyle.stroke] or [PaintingStyle.strokeAndFill]. The - /// width is given in logical pixels measured in the direction - /// orthogonal to the direction of the path. - /// - /// The values null and 0.0 correspond to a hairline width. double get strokeWidth; set strokeWidth(double value); - - /// The kind of finish to place on the end of lines drawn when - /// [style] is set to [PaintingStyle.stroke] or - /// [PaintingStyle.strokeAndFill]. - /// - /// If null, defaults to [StrokeCap.butt], i.e. no caps. StrokeCap get strokeCap; set strokeCap(StrokeCap value); - - /// The kind of finish to use for line segment joins. - /// [style] is set to [PaintingStyle.stroke] or - /// [PaintingStyle.strokeAndFill]. Only applies to drawPath not drawPoints. - /// - /// If null, defaults to [StrokeCap.butt], i.e. no caps. StrokeJoin get strokeJoin; set strokeJoin(StrokeJoin value); - - /// Whether to apply anti-aliasing to lines and images drawn on the - /// canvas. - /// - /// Defaults to true. The value null is treated as false. bool get isAntiAlias; set isAntiAlias(bool value); Color get color; set color(Color value); - - /// Whether the colors of the image are inverted when drawn. - /// - /// Inverting the colors of an image applies a new color filter that will - /// be composed with any user provided color filters. This is primarily - /// used for implementing smart invert on iOS. bool get invertColors; set invertColors(bool value); - - /// The shader to use when stroking or filling a shape. - /// - /// When this is null, the [color] is used instead. - /// - /// See also: - /// - /// * [Gradient], a shader that paints a color gradient. - /// * [ImageShader], a shader that tiles an [Image]. - /// * [colorFilter], which overrides [shader]. - /// * [color], which is used if [shader] and [colorFilter] are null. Shader? get shader; set shader(Shader? value); - - /// A mask filter (for example, a blur) to apply to a shape after it has been - /// drawn but before it has been composited into the image. - /// - /// See [MaskFilter] for details. MaskFilter? get maskFilter; set maskFilter(MaskFilter? value); - - /// Controls the performance vs quality trade-off to use when applying - /// filters, such as [maskFilter], or when drawing images, as with - /// [Canvas.drawImageRect] or [Canvas.drawImageNine]. - /// - /// Defaults to [FilterQuality.none]. // TODO(ianh): verify that the image drawing methods actually respect this FilterQuality get filterQuality; set filterQuality(FilterQuality value); - - /// A color filter to apply when a shape is drawn or when a layer is - /// composited. - /// - /// See [ColorFilter] for details. - /// - /// When a shape is being drawn, [colorFilter] overrides [color] and [shader]. ColorFilter? get colorFilter; set colorFilter(ColorFilter? value); double get strokeMiterLimit; set strokeMiterLimit(double value); - - /// The [ImageFilter] to use when drawing raster images. - /// - /// For example, to blur an image using [Canvas.drawImage], apply an - /// [ImageFilter.blur]: - /// - /// ```dart - /// import 'dart:ui' as ui; - /// - /// ui.Image image; - /// - /// void paint(Canvas canvas, Size size) { - /// canvas.drawImage( - /// image, - /// Offset.zero, - /// Paint()..imageFilter = ui.ImageFilter.blur(sigmaX: .5, sigmaY: .5), - /// ); - /// } - /// ``` - /// - /// See also: - /// - /// * [MaskFilter], which is used for drawing geometry. ImageFilter? get imageFilter; set imageFilter(ImageFilter? value); } -/// Base class for objects such as [Gradient] and [ImageShader] which -/// correspond to shaders as used by [Paint.shader]. abstract class Shader { - /// This class is created by the engine, and should not be instantiated - /// or extended directly. Shader._(); } -/// A shader (as used by [Paint.shader]) that renders a color gradient. -/// -/// There are several types of gradients, represented by the various -/// constructors on this class. abstract class Gradient extends Shader { - /// Creates a linear gradient from `from` to `to`. - /// - /// If `colorStops` is provided, `colorStops[i]` is a number from 0.0 to 1.0 - /// that specifies where `color[i]` begins in the gradient. If `colorStops` is - /// not provided, then only two stops, at 0.0 and 1.0, are implied (and - /// `color` must therefore only have two entries). - /// - /// The behavior before `from` and after `to` is described by the `tileMode` - /// argument. For details, see the [TileMode] enum. - /// - /// ![](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/tile_mode_clamp_linear.png) - /// ![](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/tile_mode_mirror_linear.png) - /// ![](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/tile_mode_repeated_linear.png) - /// - /// If `from`, `to`, `colors`, or `tileMode` are null, or if `colors` or - /// `colorStops` contain null values, this constructor will throw a - /// [NoSuchMethodError]. factory Gradient.linear( Offset from, Offset to, @@ -1100,36 +281,6 @@ abstract class Gradient extends Shader { ]) => engine.experimentalUseSkia ? engine.CkGradientLinear(from, to, colors, colorStops, tileMode, matrix4) : engine.GradientLinear(from, to, colors, colorStops, tileMode, matrix4); - - /// Creates a radial gradient centered at `center` that ends at `radius` - /// distance from the center. - /// - /// If `colorStops` is provided, `colorStops[i]` is a number from 0.0 to 1.0 - /// that specifies where `color[i]` begins in the gradient. If `colorStops` is - /// not provided, then only two stops, at 0.0 and 1.0, are implied (and - /// `color` must therefore only have two entries). - /// - /// The behavior before and after the radius is described by the `tileMode` - /// argument. For details, see the [TileMode] enum. - /// - /// ![](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/tile_mode_clamp_radial.png) - /// ![](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/tile_mode_mirror_radial.png) - /// ![](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/tile_mode_repeated_radial.png) - /// - /// If `center`, `radius`, `colors`, or `tileMode` are null, or if `colors` or - /// `colorStops` contain null values, this constructor will throw a - /// [NoSuchMethodError]. - /// - /// If `matrix4` is provided, the gradient fill will be transformed by the - /// specified 4x4 matrix relative to the local coordinate system. `matrix4` - /// must be a column-major matrix packed into a list of 16 values. - /// - /// If `focal` is provided and not equal to `center` and `focalRadius` is - /// provided and not equal to 0.0, the generated shader will be a two point - /// conical radial gradient, with `focal` being the center of the focal - /// circle and `focalRadius` being the radius of that circle. If `focal` is - /// provided and not equal to `center`, at least one of the two offsets must - /// not be equal to [Offset.zero]. factory Gradient.radial( Offset center, double radius, @@ -1143,51 +294,21 @@ abstract class Gradient extends Shader { _validateColorStops(colors, colorStops); // If focal is null or focal radius is null, this should be treated as a regular radial gradient // If focal == center and the focal radius is 0.0, it's still a regular radial gradient - final Float32List? matrix32 = - matrix4 != null ? engine.toMatrix32(matrix4) : null; + final Float32List? matrix32 = matrix4 != null ? engine.toMatrix32(matrix4) : null; if (focal == null || (focal == center && focalRadius == 0.0)) { return engine.experimentalUseSkia - ? engine.CkGradientRadial( - center, radius, colors, colorStops, tileMode, matrix32) - : engine.GradientRadial( - center, radius, colors, colorStops, tileMode, matrix32); + ? engine.CkGradientRadial(center, radius, colors, colorStops, tileMode, matrix32) + : engine.GradientRadial(center, radius, colors, colorStops, tileMode, matrix32); } else { assert(center != Offset.zero || focal != Offset.zero); // will result in exception(s) in Skia side return engine.experimentalUseSkia - ? engine.CkGradientConical(focal, focalRadius, center, radius, colors, - colorStops, tileMode, matrix32) - : engine.GradientConical(focal, focalRadius, center, radius, colors, - colorStops, tileMode, matrix32); + ? engine.CkGradientConical( + focal, focalRadius, center, radius, colors, colorStops, tileMode, matrix32) + : engine.GradientConical( + focal, focalRadius, center, radius, colors, colorStops, tileMode, matrix32); } } - - /// Creates a sweep gradient centered at `center` that starts at `startAngle` - /// and ends at `endAngle`. - /// - /// `startAngle` and `endAngle` should be provided in radians, with zero - /// radians being the horizontal line to the right of the `center` and with - /// positive angles going clockwise around the `center`. - /// - /// If `colorStops` is provided, `colorStops[i]` is a number from 0.0 to 1.0 - /// that specifies where `color[i]` begins in the gradient. If `colorStops` is - /// not provided, then only two stops, at 0.0 and 1.0, are implied (and - /// `color` must therefore only have two entries). - /// - /// The behavior before `startAngle` and after `endAngle` is described by the - /// `tileMode` argument. For details, see the [TileMode] enum. - /// - /// ![](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/tile_mode_clamp_sweep.png) - /// ![](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/tile_mode_mirror_sweep.png) - /// ![](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/tile_mode_repeated_sweep.png) - /// - /// If `center`, `colors`, `tileMode`, `startAngle`, or `endAngle` are null, - /// or if `colors` or `colorStops` contain null values, this constructor will - /// throw a [NoSuchMethodError]. - /// - /// If `matrix4` is provided, the gradient fill will be transformed by the - /// specified 4x4 matrix relative to the local coordinate system. `matrix4` - /// must be a column-major matrix packed into a list of 16 values. factory Gradient.sweep( Offset center, List colors, [ @@ -1203,176 +324,33 @@ abstract class Gradient extends Shader { endAngle, matrix4 != null ? engine.toMatrix32(matrix4) : null); } -/// Opaque handle to raw decoded image data (pixels). -/// -/// To obtain an [Image] object, use [instantiateImageCodec]. -/// -/// To draw an [Image], use one of the methods on the [Canvas] class, such as -/// [Canvas.drawImage]. abstract class Image { - /// The number of image pixels along the image's horizontal axis. int get width; - - /// The number of image pixels along the image's vertical axis. int get height; - - /// Converts the [Image] object into a byte array. - /// - /// The [format] argument specifies the format in which the bytes will be - /// returned. - /// - /// Returns a future that completes with the binary image data or an error - /// if encoding fails. - Future toByteData( - {ImageByteFormat format = ImageByteFormat.rawRgba}); - - /// Release the resources used by this object. The object is no longer usable - /// after this method is called. + Future toByteData({ImageByteFormat format = ImageByteFormat.rawRgba}); void dispose(); @override String toString() => '[$width\u00D7$height]'; } -/// A description of a color filter to apply when drawing a shape or compositing -/// a layer with a particular [Paint]. A color filter is a function that takes -/// two colors, and outputs one color. When applied during compositing, it is -/// independently applied to each pixel of the layer being drawn before the -/// entire layer is merged with the destination. -/// -/// Instances of this class are used with [Paint.colorFilter] on [Paint] -/// objects. abstract class ColorFilter { - /// Creates a color filter that applies the blend mode given as the second - /// argument. The source color is the one given as the first argument, and the - /// destination color is the one from the layer being composited. - /// - /// The output of this filter is then composited into the background according - /// to the [Paint.blendMode], using the output of this filter as the source - /// and the background as the destination. - const factory ColorFilter.mode(Color color, BlendMode blendMode) = - engine.EngineColorFilter.mode; - - /// Construct a color filter that transforms a color by a 4x5 matrix. - /// - /// Every pixel's color value, repsented as an `[R, G, B, A]`, is matrix - /// multiplied to create a new color: - /// - /// ``` - /// | R' | | a00 a01 a02 a03 a04 | | R | - /// | G' | = | a10 a11 a22 a33 a44 | * | G | - /// | B' | | a20 a21 a22 a33 a44 | | B | - /// | A' | | a30 a31 a22 a33 a44 | | A | - /// ``` - /// - /// The matrix is in row-major order and the translation column is specified - /// in unnormalized, 0...255, space. For example, the identity matrix is: - /// - /// ``` - /// const ColorMatrix identity = ColorFilter.matrix([ - /// 1, 0, 0, 0, 0, - /// 0, 1, 0, 0, 0, - /// 0, 0, 1, 0, 0, - /// 0, 0, 0, 1, 0, - /// ]); - /// ``` - /// - /// ## Examples - /// - /// An inversion color matrix: - /// - /// ``` - /// const ColorFilter invert = ColorFilter.matrix([ - /// -1, 0, 0, 0, 255, - /// 0, -1, 0, 0, 255, - /// 0, 0, -1, 0, 255, - /// 0, 0, 0, 1, 0, - /// ]); - /// ``` - /// - /// A sepia-toned color matrix (values based on the [Filter Effects Spec](https://www.w3.org/TR/filter-effects-1/#sepiaEquivalent)): - /// - /// ``` - /// const ColorFilter sepia = ColorFilter.matrix([ - /// 0.393, 0.769, 0.189, 0, 0, - /// 0.349, 0.686, 0.168, 0, 0, - /// 0.272, 0.534, 0.131, 0, 0, - /// 0, 0, 0, 1, 0, - /// ]); - /// ``` - /// - /// A greyscale color filter (values based on the [Filter Effects Spec](https://www.w3.org/TR/filter-effects-1/#grayscaleEquivalent)): - /// - /// ``` - /// const ColorFilter greyscale = ColorFilter.matrix([ - /// 0.2126, 0.7152, 0.0722, 0, 0, - /// 0.2126, 0.7152, 0.0722, 0, 0, - /// 0.2126, 0.7152, 0.0722, 0, 0, - /// 0, 0, 0, 1, 0, - /// ]); - /// ``` - const factory ColorFilter.matrix(List matrix) = - engine.EngineColorFilter.matrix; - - /// Construct a color filter that applies the sRGB gamma curve to the RGB - /// channels. - const factory ColorFilter.linearToSrgbGamma() = - engine.EngineColorFilter.linearToSrgbGamma; - - /// Creates a color filter that applies the inverse of the sRGB gamma curve - /// to the RGB channels. - const factory ColorFilter.srgbToLinearGamma() = - engine.EngineColorFilter.srgbToLinearGamma; + const factory ColorFilter.mode(Color color, BlendMode blendMode) = engine.EngineColorFilter.mode; + const factory ColorFilter.matrix(List matrix) = engine.EngineColorFilter.matrix; + const factory ColorFilter.linearToSrgbGamma() = engine.EngineColorFilter.linearToSrgbGamma; + const factory ColorFilter.srgbToLinearGamma() = engine.EngineColorFilter.srgbToLinearGamma; } -/// Styles to use for blurs in [MaskFilter] objects. // These enum values must be kept in sync with SkBlurStyle. enum BlurStyle { // These mirror SkBlurStyle and must be kept in sync. - - /// Fuzzy inside and outside. This is useful for painting shadows that are - /// offset from the shape that ostensibly is casting the shadow. normal, - - /// Solid inside, fuzzy outside. This corresponds to drawing the shape, and - /// additionally drawing the blur. This can make objects appear brighter, - /// maybe even as if they were fluorescent. solid, - - /// Nothing inside, fuzzy outside. This is useful for painting shadows for - /// partially transparent shapes, when they are painted separately but without - /// an offset, so that the shadow doesn't paint below the shape. outer, - - /// Fuzzy inside, nothing outside. This can make shapes appear to be lit from - /// within. inner, } -/// A mask filter to apply to shapes as they are painted. A mask filter is a -/// function that takes a bitmap of color pixels, and returns another bitmap of -/// color pixels. -/// -/// Instances of this class are used with [Paint.maskFilter] on [Paint] objects. class MaskFilter { - /// Creates a mask filter that takes the shape being drawn and blurs it. - /// - /// This is commonly used to approximate shadows. - /// - /// The `style` argument controls the kind of effect to draw; see [BlurStyle]. - /// - /// The `sigma` argument controls the size of the effect. It is the standard - /// deviation of the Gaussian blur to apply. The value must be greater than - /// zero. The sigma corresponds to very roughly half the radius of the effect - /// in pixels. - /// - /// A blur is an expensive operation and should therefore be used sparingly. - /// - /// The arguments must not be null. - /// - /// See also: - /// - /// * [Canvas.drawShadow], which is a more efficient way to draw shadows. const MaskFilter.blur( this._style, this._sigma, @@ -1381,18 +359,14 @@ class MaskFilter { final BlurStyle _style; final double _sigma; - - /// On the web returns the value of sigma passed to [MaskFilter.blur]. double get webOnlySigma => _sigma; - - /// On the web returns the value of `style` passed to [MaskFilter.blur]. BlurStyle get webOnlyBlurStyle => _style; @override bool operator ==(Object other) { - return other is MaskFilter && - other._style == _style && - other._sigma == _sigma; + return other is MaskFilter + && other._style == _style + && other._sigma == _sigma; } @override @@ -1402,44 +376,16 @@ class MaskFilter { String toString() => 'MaskFilter.blur($_style, ${_sigma.toStringAsFixed(1)})'; } -/// Quality levels for image filters. -/// -/// See [Paint.filterQuality]. enum FilterQuality { // This list comes from Skia's SkFilterQuality.h and the values (order) should // be kept in sync. - - /// Fastest possible filtering, albeit also the lowest quality. - /// - /// Typically this implies nearest-neighbour filtering. none, - - /// Better quality than [none], faster than [medium]. - /// - /// Typically this implies bilinear interpolation. low, - - /// Better quality than [low], faster than [high]. - /// - /// Typically this implies a combination of bilinear interpolation and - /// pyramidal parametric prefiltering (mipmaps). medium, - - /// Best possible quality filtering, albeit also the slowest. - /// - /// Typically this implies bicubic interpolation or better. high, } -/// A filter operation to apply to a raster image. -/// -/// See also: -/// -/// * [BackdropFilter], a widget that applies [ImageFilter] to its rendering. -/// * [SceneBuilder.pushBackdropFilter], which is the low-level API for using -/// this class. class ImageFilter { - /// Creates an image filter that applies a Gaussian blur. factory ImageFilter.blur({double sigmaX = 0.0, double sigmaY = 0.0}) { if (engine.experimentalUseSkia) { return engine.CkImageFilter.blur(sigmaX: sigmaX, sigmaY: sigmaY); @@ -1447,128 +393,46 @@ class ImageFilter { return engine.EngineImageFilter.blur(sigmaX: sigmaX, sigmaY: sigmaY); } - ImageFilter.matrix(Float64List matrix4, - {FilterQuality filterQuality = FilterQuality.low}) { + ImageFilter.matrix(Float64List matrix4, {FilterQuality filterQuality = FilterQuality.low}) { // TODO(flutter_web): add implementation. - throw UnimplementedError( - 'ImageFilter.matrix not implemented for web platform.'); + throw UnimplementedError('ImageFilter.matrix not implemented for web platform.'); // if (matrix4.length != 16) // throw ArgumentError('"matrix4" must have 16 entries.'); } } -/// The format in which image bytes should be returned when using -/// [Image.toByteData]. enum ImageByteFormat { - /// Raw RGBA format. - /// - /// Unencoded bytes, in RGBA row-primary form, 8 bits per channel. rawRgba, - - /// Raw unmodified format. - /// - /// Unencoded bytes, in the image's existing format. For example, a grayscale - /// image may use a single 8-bit channel for each pixel. rawUnmodified, - - /// PNG format. - /// - /// A loss-less compression format for images. This format is well suited for - /// images with hard edges, such as screenshots or sprites, and images with - /// text. Transparency is supported. The PNG format supports images up to - /// 2,147,483,647 pixels in either dimension, though in practice available - /// memory provides a more immediate limitation on maximum image size. - /// - /// PNG images normally use the `.png` file extension and the `image/png` MIME - /// type. - /// - /// See also: - /// - /// * , the Wikipedia page on PNG. - /// * , the PNG standard. png, } -/// The format of pixel data given to [decodeImageFromPixels]. enum PixelFormat { - /// Each pixel is 32 bits, with the highest 8 bits encoding red, the next 8 - /// bits encoding green, the next 8 bits encoding blue, and the lowest 8 bits - /// encoding alpha. rgba8888, - - /// Each pixel is 32 bits, with the highest 8 bits encoding blue, the next 8 - /// bits encoding green, the next 8 bits encoding red, and the lowest 8 bits - /// encoding alpha. bgra8888, } -/// Callback signature for [decodeImageFromList]. typedef ImageDecoderCallback = void Function(Image result); -/// Information for a single frame of an animation. -/// -/// To obtain an instance of the [FrameInfo] interface, see -/// [Codec.getNextFrame]. abstract class FrameInfo { - /// This class is created by the engine, and should not be instantiated - /// or extended directly. - /// - /// To obtain an instance of the [FrameInfo] interface, see - /// [Codec.getNextFrame]. FrameInfo._(); - - /// The duration this frame should be shown. Duration get duration => Duration(milliseconds: _durationMillis); int get _durationMillis => 0; - - /// The [Image] object for this frame. Image get image; } -/// A handle to an image codec. class Codec { - /// This class is created by the engine, and should not be instantiated - /// or extended directly. - /// - /// To obtain an instance of the [Codec] interface, see - /// [instantiateImageCodec]. Codec._(); - - /// Number of frames in this image. int get frameCount => 0; - - /// Number of times to repeat the animation. - /// - /// * 0 when the animation should be played once. - /// * -1 for infinity repetitions. int get repetitionCount => 0; - - /// Fetches the next animation frame. - /// - /// Wraps back to the first frame after returning the last frame. - /// - /// The returned future can complete with an error if the decoding has failed. Future getNextFrame() { return engine.futurize(_getNextFrame); } - /// Returns an error message on failure, null on success. String? _getNextFrame(engine.Callback callback) => null; - - /// Release the resources used by this object. The object is no longer usable - /// after this method is called. void dispose() {} } -/// Instantiates an image codec [Codec] object. -/// -/// [list] is the binary image data (e.g a PNG or GIF binary data). -/// The data can be for either static or animated images. -/// -/// The following image formats are supported: {@macro flutter.dart:ui.imageFormats} -/// -/// The returned future can complete with an error if the image decoding has -/// failed. Future instantiateImageCodec( Uint8List list, { int? targetWidth, @@ -1580,9 +444,6 @@ Future instantiateImageCodec( _instantiateImageCodec(list, callback)); } -/// Instantiates a [Codec] object for an image binary data. -/// -/// Returns an error message if the instantiation has failed, null otherwise. String? _instantiateImageCodec( Uint8List list, engine.Callback callback, { @@ -1597,8 +458,7 @@ String? _instantiateImageCodec( } else { assert(height != null); assert(format != null); - engine.skiaInstantiateImageCodec( - list, callback, width, height, format!.index, rowBytes); + engine.skiaInstantiateImageCodec(list, callback, width, height, format!.index, rowBytes); } return null; } @@ -1614,12 +474,12 @@ Future webOnlyInstantiateImageCodecFromUrl(Uri uri, } String? _instantiateImageCodecFromUrl( - Uri uri, - engine.WebOnlyImageCodecChunkCallback? chunkCallback, - engine.Callback callback) { + Uri uri, + engine.WebOnlyImageCodecChunkCallback? chunkCallback, + engine.Callback callback, +) { if (engine.experimentalUseSkia) { - engine.skiaInstantiateWebImageCodec( - uri.toString(), callback, chunkCallback); + engine.skiaInstantiateWebImageCodec(uri.toString(), callback, chunkCallback); return null; } else { callback(engine.HtmlCodec(uri.toString(), chunkCallback: chunkCallback)); @@ -1627,28 +487,16 @@ String? _instantiateImageCodecFromUrl( } } -/// Loads a single image frame from a byte array into an [Image] object. -/// -/// This is a convenience wrapper around [instantiateImageCodec]. -/// Prefer using [instantiateImageCodec] which also supports multi frame images. void decodeImageFromList(Uint8List list, ImageDecoderCallback callback) { _decodeImageFromListAsync(list, callback); } -Future _decodeImageFromListAsync( - Uint8List list, ImageDecoderCallback callback) async { +Future _decodeImageFromListAsync(Uint8List list, ImageDecoderCallback callback) async { final Codec codec = await instantiateImageCodec(list); final FrameInfo frameInfo = await codec.getNextFrame(); callback(frameInfo.image); } -/// Convert an array of pixel values into an [Image] object. -/// -/// [pixels] is the pixel data in the encoding described by [format]. -/// -/// [rowBytes] is the number of bytes consumed by each row of pixels in the -/// data buffer. If unspecified, it defaults to [width] multipled by the -/// number of bytes per pixel in the provided [format]. void decodeImageFromPixels( Uint8List pixels, int width, @@ -1660,8 +508,7 @@ void decodeImageFromPixels( int? targetHeight, bool allowUpscaling = true, }) { - final Future codecFuture = - _futurize((engine.Callback callback) { + final Future codecFuture = _futurize((engine.Callback callback) { return _instantiateImageCodec( pixels, callback, @@ -1676,20 +523,7 @@ void decodeImageFromPixels( .then((FrameInfo frameInfo) => callback(frameInfo.image)); } -/// A single shadow. -/// -/// Multiple shadows are stacked together in a [TextStyle]. class Shadow { - /// Construct a shadow. - /// - /// The default shadow is a black shadow with zero offset and zero blur. - /// Default shadows should be completely covered by the casting element, - /// and not be visble. - /// - /// Transparency should be adjusted through the [color] alpha. - /// - /// Shadow order matters due to compositing multiple translucent objects not - /// being commutative. const Shadow({ this.color = const Color(_kColorDefault), this.offset = Offset.zero, @@ -1702,55 +536,22 @@ class Shadow { 'Text shadow blur radius should be non-negative.'); static const int _kColorDefault = 0xFF000000; - - /// Color that the shadow will be drawn with. - /// - /// The shadows are shapes composited directly over the base canvas, and do not - /// represent optical occlusion. final Color color; - - /// The displacement of the shadow from the casting element. - /// - /// Positive x/y offsets will shift the shadow to the right and down, while - /// negative offsets shift the shadow to the left and up. The offsets are - /// relative to the position of the element that is casting it. final Offset offset; - - /// The standard deviation of the Gaussian to convolve with the shadow's shape. final double blurRadius; - - /// Converts a blur radius in pixels to sigmas. - /// - /// See the sigma argument to [MaskFilter.blur]. - /// // See SkBlurMask::ConvertRadiusToSigma(). // static double convertRadiusToSigma(double radius) { return radius * 0.57735 + 0.5; } - /// The [blurRadius] in sigmas instead of logical pixels. - /// - /// See the sigma argument to [MaskFilter.blur]. double get blurSigma => convertRadiusToSigma(blurRadius); - - /// Create the [Paint] object that corresponds to this shadow description. - /// - /// The [offset] is not represented in the [Paint] object. - /// To honor this as well, the shape should be translated by [offset] before - /// being filled using this [Paint]. - /// - /// This class does not provide a way to disable shadows to avoid inconsistencies - /// in shadow blur rendering, primarily as a method of reducing test flakiness. - /// [toPaint] should be overriden in subclasses to provide this functionality. Paint toPaint() { return Paint() ..color = color ..maskFilter = MaskFilter.blur(BlurStyle.normal, blurSigma); } - /// Returns a new shadow with its [offset] and [blurRadius] scaled by the given - /// factor. Shadow scale(double factor) { return Shadow( color: color, @@ -1759,25 +560,6 @@ class Shadow { ); } - /// Linearly interpolate between two shadows. - /// - /// If either shadow is null, this function linearly interpolates from a - /// a shadow that matches the other shadow in color but has a zero - /// offset and a zero blurRadius. - /// - /// {@template dart.ui.shadow.lerp} - /// The `t` argument represents position on the timeline, with 0.0 meaning - /// that the interpolation has not started, returning `a` (or something - /// equivalent to `a`), 1.0 meaning that the interpolation has finished, - /// returning `b` (or something equivalent to `b`), and values in between - /// meaning that the interpolation is at the relevant point on the timeline - /// between `a` and `b`. The interpolation can be extrapolated beyond 0.0 and - /// 1.0, so negative values and values greater than 1.0 are valid (and can - /// easily be generated by curves such as [Curves.elasticInOut]). - /// - /// Values for `t` are usually obtained from an [Animation], such as - /// an [AnimationController]. - /// {@endtemplate} static Shadow? lerp(Shadow? a, Shadow? b, double t) { assert(t != null); // ignore: unnecessary_null_comparison if (b == null) { @@ -1799,11 +581,6 @@ class Shadow { } } - /// Linearly interpolate between two lists of shadows. - /// - /// If the lists differ in length, excess items are lerped with null. - /// - /// {@macro dart.ui.shadow.lerp} static List? lerpList(List? a, List? b, double t) { assert(t != null); // ignore: unnecessary_null_comparison if (a == null && b == null) { @@ -1841,15 +618,8 @@ class Shadow { String toString() => 'TextShadow($color, $offset, $blurRadius)'; } -/// A shader (as used by [Paint.shader]) that tiles an image. class ImageShader extends Shader { - /// Creates an image-tiling shader. The first argument specifies the image to - /// tile. The second and third arguments specify the [TileMode] for the x - /// direction and y direction respectively. The fourth argument gives the - /// matrix to apply to the effect. All the arguments are required and must not - /// be null. - factory ImageShader( - Image image, TileMode tmx, TileMode tmy, Float64List matrix4) { + factory ImageShader(Image image, TileMode tmx, TileMode tmy, Float64List matrix4) { if (engine.experimentalUseSkia) { return engine.CkImageShader(image, tmx, tmy, matrix4); } @@ -1857,12 +627,8 @@ class ImageShader extends Shader { } } -/// A handle to a read-only byte buffer that is managed by the engine. class ImmutableBuffer { ImmutableBuffer._(this.length); - - /// Creates a copy of the data from a [Uint8List] suitable for internal use - /// in the engine. static Future fromUint8List(Uint8List list) async { final ImmutableBuffer instance = ImmutableBuffer._(list.length); instance._list = list; @@ -1870,41 +636,22 @@ class ImmutableBuffer { } Uint8List? _list; - - /// The length, in bytes, of the underlying data. final int length; - - /// Release the resources used by this object. The object is no longer usable - /// after this method is called. void dispose() => _list = null; } -/// A descriptor of data that can be turned into an [Image] via a [Codec]. -/// -/// Use this class to determine the height, width, and byte size of image data -/// before decoding it. class ImageDescriptor { ImageDescriptor._() : _width = null, _height = null, _rowBytes = null, _format = null; - - /// Creates an image descriptor from encoded data in a supported format. static Future encoded(ImmutableBuffer buffer) async { final ImageDescriptor descriptor = ImageDescriptor._(); descriptor._data = buffer._list; return descriptor; } - /// Creates an image descriptor from raw image pixels. - /// - /// The `pixels` parameter is the pixel data in the encoding described by - /// `format`. - /// - /// The `rowBytes` parameter is the number of bytes consumed by each row of - /// pixels in the data buffer. If unspecified, it defaults to `width` multiplied - /// by the number of bytes per pixel in the provided `format`. // Not async because there's no expensive work to do here. ImageDescriptor.raw( ImmutableBuffer buffer, { @@ -1926,26 +673,14 @@ class ImageDescriptor { final PixelFormat? _format; Never _throw(String parameter) { - throw UnsupportedError( - 'ImageDescriptor.$parameter is not supported on web.'); + throw UnsupportedError('ImageDescriptor.$parameter is not supported on web.'); } - /// The width, in pixels, of the image. int get width => _width ?? _throw('width'); - - /// The height, in pixels, of the image. int get height => _height ?? _throw('height'); - - /// The number of bytes per pixel in the image. - int get bytesPerPixel => throw UnsupportedError( - 'ImageDescriptor.bytesPerPixel is not supported on web.'); - - /// Release the resources used by this object. The object is no longer usable - /// after this method is called. + int get bytesPerPixel => + throw UnsupportedError('ImageDescriptor.bytesPerPixel is not supported on web.'); void dispose() => _data = null; - - /// Creates a [Codec] object which is suitable for decoding the data in the - /// buffer to an [Image]. Future instantiateCodec({int? targetWidth, int? targetHeight}) { if (_data == null) { throw StateError('Object is disposed'); diff --git a/engine/src/flutter/lib/web_ui/lib/src/ui/path.dart b/engine/src/flutter/lib/web_ui/lib/src/ui/path.dart index 1514d2432f..02d4e40d73 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/ui/path.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/ui/path.dart @@ -5,25 +5,7 @@ // @dart = 2.10 part of ui; -/// A complex, one-dimensional subset of a plane. -/// -/// A path consists of a number of subpaths, and a _current point_. -/// -/// Subpaths consist of segments of various types, such as lines, -/// arcs, or beziers. Subpaths can be open or closed, and can -/// self-intersect. -/// -/// Closed subpaths enclose a (possibly discontiguous) region of the -/// plane based on the current [fillType]. -/// -/// The _current point_ is initially at the origin. After each -/// operation adding a segment to a subpath, the current point is -/// updated to the end of that segment. -/// -/// Paths can be drawn on canvases using [Canvas.drawPath], and can -/// used to create clip regions using [Canvas.clipPath]. abstract class Path { - /// Create a new empty [Path] object. factory Path() { if (engine.experimentalUseSkia) { return engine.CkPath(); @@ -31,11 +13,6 @@ abstract class Path { return engine.SurfacePath(); } } - - /// Creates a copy of another [Path]. - /// - /// This copy is fast and does not require additional memory unless either - /// the `source` path or the path returned by this constructor are modified. factory Path.from(Path source) { if (engine.experimentalUseSkia) { return engine.CkPath.from(source as engine.CkPath); @@ -43,231 +20,47 @@ abstract class Path { return engine.SurfacePath.from(source as engine.SurfacePath); } } - - /// Determines how the interior of this path is calculated. - /// - /// Defaults to the non-zero winding rule, [PathFillType.nonZero]. PathFillType get fillType; set fillType(PathFillType value); - - /// Starts a new subpath at the given coordinate. void moveTo(double x, double y); - - /// Starts a new subpath at the given offset from the current point. void relativeMoveTo(double dx, double dy); - - /// Adds a straight line segment from the current point to the given - /// point. void lineTo(double x, double y); - - /// Adds a straight line segment from the current point to the point - /// at the given offset from the current point. void relativeLineTo(double dx, double dy); - - /// Adds a quadratic bezier segment that curves from the current - /// point to the given point (x2,y2), using the control point - /// (x1,y1). void quadraticBezierTo(double x1, double y1, double x2, double y2); - - /// Adds a quadratic bezier segment that curves from the current - /// point to the point at the offset (x2,y2) from the current point, - /// using the control point at the offset (x1,y1) from the current - /// point. void relativeQuadraticBezierTo(double x1, double y1, double x2, double y2); - - /// Adds a cubic bezier segment that curves from the current point - /// to the given point (x3,y3), using the control points (x1,y1) and - /// (x2,y2). - void cubicTo( - double x1, double y1, double x2, double y2, double x3, double y3); - - /// Adds a cubic bezier segment that curves from the current point - /// to the point at the offset (x3,y3) from the current point, using - /// the control points at the offsets (x1,y1) and (x2,y2) from the - /// current point. - void relativeCubicTo( - double x1, double y1, double x2, double y2, double x3, double y3); - - /// Adds a bezier segment that curves from the current point to the - /// given point (x2,y2), using the control points (x1,y1) and the - /// weight w. If the weight is greater than 1, then the curve is a - /// hyperbola; if the weight equals 1, it's a parabola; and if it is - /// less than 1, it is an ellipse. + void cubicTo(double x1, double y1, double x2, double y2, double x3, double y3); + void relativeCubicTo(double x1, double y1, double x2, double y2, double x3, double y3); void conicTo(double x1, double y1, double x2, double y2, double w); - - /// Adds a bezier segment that curves from the current point to the - /// point at the offset (x2,y2) from the current point, using the - /// control point at the offset (x1,y1) from the current point and - /// the weight w. If the weight is greater than 1, then the curve is - /// a hyperbola; if the weight equals 1, it's a parabola; and if it - /// is less than 1, it is an ellipse. void relativeConicTo(double x1, double y1, double x2, double y2, double w); - - /// If the `forceMoveTo` argument is false, adds a straight line - /// segment and an arc segment. - /// - /// If the `forceMoveTo` argument is true, starts a new subpath - /// consisting of an arc segment. - /// - /// In either case, the arc segment consists of the arc that follows - /// the edge of the oval bounded by the given rectangle, from - /// startAngle radians around the oval up to startAngle + sweepAngle - /// radians around the oval, with zero radians being the point on - /// the right hand side of the oval that crosses the horizontal line - /// that intersects the center of the rectangle and with positive - /// angles going clockwise around the oval. - /// - /// The line segment added if `forceMoveTo` is false starts at the - /// current point and ends at the start of the arc. - void arcTo( - Rect rect, double startAngle, double sweepAngle, bool forceMoveTo); - - /// Appends up to four conic curves weighted to describe an oval of `radius` - /// and rotated by `rotation`. - /// - /// The first curve begins from the last point in the path and the last ends - /// at `arcEnd`. The curves follow a path in a direction determined by - /// `clockwise` and `largeArc` in such a way that the sweep angle - /// is always less than 360 degrees. - /// - /// A simple line is appended if either either radii are zero or the last - /// point in the path is `arcEnd`. The radii are scaled to fit the last path - /// point if both are greater than zero but too small to describe an arc. - /// - /// See Conversion from endpoint to center parametrization described in - /// https://www.w3.org/TR/SVG/implnote.html#ArcConversionEndpointToCenter - /// as reference for implementation. + void arcTo(Rect rect, double startAngle, double sweepAngle, bool forceMoveTo); void arcToPoint( - Offset arcEnd, { - Radius radius = Radius.zero, - double rotation = 0.0, - bool largeArc = false, - bool clockwise = true, - }); - - /// Appends up to four conic curves weighted to describe an oval of `radius` - /// and rotated by `rotation`. - /// - /// The last path point is described by (px, py). - /// - /// The first curve begins from the last point in the path and the last ends - /// at `arcEndDelta.dx + px` and `arcEndDelta.dy + py`. The curves follow a - /// path in a direction determined by `clockwise` and `largeArc` - /// in such a way that the sweep angle is always less than 360 degrees. - /// - /// A simple line is appended if either either radii are zero, or, both - /// `arcEndDelta.dx` and `arcEndDelta.dy` are zero. The radii are scaled to - /// fit the last path point if both are greater than zero but too small to - /// describe an arc. + Offset arcEnd, { + Radius radius = Radius.zero, + double rotation = 0.0, + bool largeArc = false, + bool clockwise = true, + }); void relativeArcToPoint( - Offset arcEndDelta, { - Radius radius = Radius.zero, - double rotation = 0.0, - bool largeArc = false, - bool clockwise = true, - }); - - /// Adds a new subpath that consists of four lines that outline the - /// given rectangle. + Offset arcEndDelta, { + Radius radius = Radius.zero, + double rotation = 0.0, + bool largeArc = false, + bool clockwise = true, + }); void addRect(Rect rect); - - /// Adds a new subpath that consists of a curve that forms the - /// ellipse that fills the given rectangle. - /// - /// To add a circle, pass an appropriate rectangle as `oval`. - /// [Rect.fromCircle] can be used to easily describe the circle's center - /// [Offset] and radius. void addOval(Rect oval); - - /// Adds a new subpath with one arc segment that consists of the arc - /// that follows the edge of the oval bounded by the given - /// rectangle, from startAngle radians around the oval up to - /// startAngle + sweepAngle radians around the oval, with zero - /// radians being the point on the right hand side of the oval that - /// crosses the horizontal line that intersects the center of the - /// rectangle and with positive angles going clockwise around the - /// oval. void addArc(Rect oval, double startAngle, double sweepAngle); - - /// Adds a new subpath with a sequence of line segments that connect the given - /// points. - /// - /// If `close` is true, a final line segment will be added that connects the - /// last point to the first point. - /// - /// The `points` argument is interpreted as offsets from the origin. void addPolygon(List points, bool close); - - /// Adds a new subpath that consists of the straight lines and - /// curves needed to form the rounded rectangle described by the - /// argument. void addRRect(RRect rrect); - - /// Adds a new subpath that consists of the given `path` offset by the given - /// `offset`. - /// - /// If `matrix4` is specified, the path will be transformed by this matrix - /// after the matrix is translated by the given offset. The matrix is a 4x4 - /// matrix stored in column major order. void addPath(Path path, Offset offset, {Float64List? matrix4}); - - /// Adds the given path to this path by extending the current segment of this - /// path with the first segment of the given path. - /// - /// If `matrix4` is specified, the path will be transformed by this matrix - /// after the matrix is translated by the given `offset`. The matrix is a 4x4 - /// matrix stored in column major order. void extendWithPath(Path path, Offset offset, {Float64List? matrix4}); - - /// Closes the last subpath, as if a straight line had been drawn - /// from the current point to the first point of the subpath. void close(); - - /// Clears the [Path] object of all subpaths, returning it to the - /// same state it had when it was created. The _current point_ is - /// reset to the origin. void reset(); - - /// Tests to see if the given point is within the path. (That is, whether the - /// point would be in the visible portion of the path if the path was used - /// with [Canvas.clipPath].) - /// - /// The `point` argument is interpreted as an offset from the origin. - /// - /// Returns true if the point is in the path, and false otherwise. bool contains(Offset point); - - /// Returns a copy of the path with all the segments of every - /// subpath translated by the given offset. Path shift(Offset offset); - - /// Returns a copy of the path with all the segments of every - /// sub path transformed by the given matrix. Path transform(Float64List matrix4); - - /// Computes the bounding rectangle for this path. - /// - /// A path containing only axis-aligned points on the same straight line will - /// have no area, and therefore `Rect.isEmpty` will return true for such a - /// path. Consider checking `rect.width + rect.height > 0.0` instead, or - /// using the [computeMetrics] API to check the path length. - /// - /// For many more elaborate paths, the bounds may be inaccurate. For example, - /// when a path contains a circle, the points used to compute the bounds are - /// the circle's implied control points, which form a square around the - /// circle; if the circle has a transformation applied using [transform] then - /// that square is rotated, and the (axis-aligned, non-rotated) bounding box - /// therefore ends up grossly overestimating the actual area covered by the - /// circle. // see https://skia.org/user/api/SkPath_Reference#SkPath_getBounds Rect getBounds(); - - /// Combines the two paths according to the manner specified by the given - /// `operation`. - /// - /// The resulting path will be constructed from non-overlapping contours. The - /// curve order is reduced where possible so that cubics may be turned into - /// quadratics, and quadratics maybe turned into lines. static Path combine(PathOperation operation, Path path1, Path path2) { assert(path1 != null); // ignore: unnecessary_null_comparison assert(path2 != null); // ignore: unnecessary_null_comparison @@ -277,9 +70,5 @@ abstract class Path { throw UnimplementedError(); } - /// Creates a [PathMetrics] object for this path. - /// - /// If `forceClosed` is set to true, the contours of the path will be measured - /// as if they had been closed, even if they were not explicitly closed. PathMetrics computeMetrics({bool forceClosed = false}); } diff --git a/engine/src/flutter/lib/web_ui/lib/src/ui/path_metrics.dart b/engine/src/flutter/lib/web_ui/lib/src/ui/path_metrics.dart index b65e2b9288..65f07f881f 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/ui/path_metrics.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/ui/path_metrics.dart @@ -5,28 +5,11 @@ // @dart = 2.10 part of ui; -/// An iterable collection of [PathMetric] objects describing a [Path]. -/// -/// A [PathMetrics] object is created by using the [Path.computeMetrics] method, -/// and represents the path as it stood at the time of the call. Subsequent -/// modifications of the path do not affect the [PathMetrics] object. -/// -/// Each path metric corresponds to a segment, or contour, of a path. -/// -/// For example, a path consisting of a [Path.lineTo], a [Path.moveTo], and -/// another [Path.lineTo] will contain two contours and thus be represented by -/// two [PathMetric] objects. -/// -/// This iterable does not memoize. Callers who need to traverse the list -/// multiple times, or who need to randomly access elements of the list, should -/// use [toList] on this object. abstract class PathMetrics extends collection.IterableBase { @override Iterator get iterator; } -/// Used by [PathMetrics] to track iteration from one segment of a path to the -/// next for measurement. abstract class PathMetricIterator implements Iterator { @override PathMetric get current; @@ -35,114 +18,23 @@ abstract class PathMetricIterator implements Iterator { bool moveNext(); } -/// Utilities for measuring a [Path] and extracting sub-paths. -/// -/// Iterate over the object returned by [Path.computeMetrics] to obtain -/// [PathMetric] objects. Callers that want to randomly access elements or -/// iterate multiple times should use `path.computeMetrics().toList()`, since -/// [PathMetrics] does not memoize. -/// -/// Once created, the metrics are only valid for the path as it was specified -/// when [Path.computeMetrics] was called. If additional contours are added or -/// any contours are updated, the metrics need to be recomputed. Previously -/// created metrics will still refer to a snapshot of the path at the time they -/// were computed, rather than to the actual metrics for the new mutations to -/// the path. -/// -/// Implementation is based on -/// https://github.com/google/skia/blob/master/src/core/SkContourMeasure.cpp -/// to maintain consistency with native platforms. abstract class PathMetric { - /// Return the total length of the current contour. double get length; - - /// The zero-based index of the contour. - /// - /// [Path] objects are made up of zero or more contours. The first contour is - /// created once a drawing command (e.g. [Path.lineTo]) is issued. A - /// [Path.moveTo] command after a drawing command may create a new contour, - /// although it may not if optimizations are applied that determine the move - /// command did not actually result in moving the pen. - /// - /// This property is only valid with reference to its original iterator and - /// the contours of the path at the time the path's metrics were computed. If - /// additional contours were added or existing contours updated, this metric - /// will be invalid for the current state of the path. int get contourIndex; - - /// Computes the position of hte current contour at the given offset, and the - /// angle of the path at that point. - /// - /// For example, calling this method with a distance of 1.41 for a line from - /// 0.0,0.0 to 2.0,2.0 would give a point 1.0,1.0 and the angle 45 degrees - /// (but in radians). - /// - /// Returns null if the contour has zero [length]. - /// - /// The distance is clamped to the [length] of the current contour. Tangent? getTangentForOffset(double distance); - - /// Given a start and stop distance, return the intervening segment(s). - /// - /// `start` and `end` are pinned to legal values (0..[length]) - /// Returns null if the segment is 0 length or `start` > `stop`. - /// Begin the segment with a moveTo if `startWithMoveTo` is true. Path? extractPath(double start, double end, {bool startWithMoveTo = true}); - - /// Whether the contour is closed. - /// - /// Returns true if the contour ends with a call to [Path.close] (which may - /// have been implied when using [Path.addRect]) or if `forceClosed` was - /// specified as true in the call to [Path.computeMetrics]. Returns false - /// otherwise. bool get isClosed; } -/// The geometric description of a tangent: the angle at a point. -/// -/// See also: -/// * [PathMetric.getTangentForOffset], which returns the tangent of an offset -/// along a path. class Tangent { - /// Creates a [Tangent] with the given values. - /// - /// The arguments must not be null. const Tangent(this.position, this.vector) : assert(position != null), // ignore: unnecessary_null_comparison assert(vector != null); // ignore: unnecessary_null_comparison - - /// Creates a [Tangent] based on the angle rather than the vector. - /// - /// The [vector] is computed to be the unit vector at the given angle, - /// interpreted as clockwise radians from the x axis. factory Tangent.fromAngle(Offset position, double angle) { return Tangent(position, Offset(math.cos(angle), math.sin(angle))); } - - /// Position of the tangent. - /// - /// When used with [PathMetric.getTangentForOffset], this represents the - /// precise position that the given offset along the path corresponds to. final Offset position; - - /// The vector of the curve at [position]. - /// - /// When used with [PathMetric.getTangentForOffset], this is the vector of the - /// curve that is at the given offset along the path (i.e. the direction of - /// the curve at [position]). final Offset vector; - - /// The direction of the curve at [position]. - /// - /// When used with [PathMetric.getTangentForOffset], this is the angle of the - /// curve that is the given offset along the path (i.e. the direction of the - /// curve at [position]). - /// - /// This value is in radians, with 0.0 meaning pointing along the x axis in - /// the positive x-axis direction, positive numbers pointing downward toward - /// the negative y-axis, i.e. in a clockwise direction, and negative numbers - /// pointing upward toward the positive y-axis, i.e. in a counter-clockwise - /// direction. // flip the sign to be consistent with [Path.arcTo]'s `sweepAngle` double get angle => -math.atan2(vector.dy, vector.dx); } diff --git a/engine/src/flutter/lib/web_ui/lib/src/ui/pointer.dart b/engine/src/flutter/lib/web_ui/lib/src/ui/pointer.dart index e2f351cafe..0ad384b4d1 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/ui/pointer.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/ui/pointer.dart @@ -5,71 +5,31 @@ // @dart = 2.10 part of ui; -/// How the pointer has changed since the last report. enum PointerChange { - /// The input from the pointer is no longer directed towards this receiver. cancel, - - /// The device has started tracking the pointer. - /// - /// For example, the pointer might be hovering above the device, having not yet - /// made contact with the surface of the device. add, - - /// The device is no longer tracking the pointer. - /// - /// For example, the pointer might have drifted out of the device's hover - /// detection range or might have been disconnected from the system entirely. remove, - - /// The pointer has moved with respect to the device while not in contact with - /// the device. hover, - - /// The pointer has made contact with the device. down, - - /// The pointer has moved with respect to the device while in contact with the - /// device. move, - - /// The pointer has stopped making contact with the device. up, } -/// The kind of pointer device. enum PointerDeviceKind { - /// A touch-based pointer device. touch, - - /// A mouse-based pointer device. mouse, - - /// A pointer device with a stylus. stylus, - - /// A pointer device with a stylus that has been inverted. invertedStylus, - - /// An unknown pointer device. unknown } -/// The kind of [PointerDeviceKind.signal]. enum PointerSignalKind { - /// The event is not associated with a pointer signal. none, - - /// A pointer-generated scroll (e.g., mouse wheel or trackpad scroll). scroll, - - /// An unknown pointer signal kind. unknown } -/// Information about the state of a pointer. class PointerData { - /// Creates an object that represents the state of a pointer. const PointerData({ this.embedderId = 0, this.timeStamp = Duration.zero, @@ -101,214 +61,74 @@ class PointerData { this.scrollDeltaX = 0.0, this.scrollDeltaY = 0.0, }); - - /// Unique identifier that ties the [PointerEvent] to embedder event created it. - /// - /// No two pointer events can have the same [embedderId]. This is different from - /// [pointerIdentifier] - used for hit-testing, whereas [embedderId] is used to - /// identify the platform event. final int embedderId; - - /// Time of event dispatch, relative to an arbitrary timeline. final Duration timeStamp; - - /// How the pointer has changed since the last report. final PointerChange change; - - /// The kind of input device for which the event was generated. final PointerDeviceKind kind; - - /// The kind of signal for a pointer signal event. final PointerSignalKind? signalKind; - - /// Unique identifier for the pointing device, reused across interactions. final int device; - - /// Unique identifier for the pointer. - /// - /// This field changes for each new pointer down event. Framework uses this - /// identifier to determine hit test result. final int pointerIdentifier; - - /// X coordinate of the position of the pointer, in physical pixels in the - /// global coordinate space. final double physicalX; - - /// Y coordinate of the position of the pointer, in physical pixels in the - /// global coordinate space. final double physicalY; - - /// The distance of pointer movement on X coordinate in physical pixels. final double physicalDeltaX; - - /// The distance of pointer movement on Y coordinate in physical pixels. final double physicalDeltaY; - - /// Bit field using the *Button constants (primaryMouseButton, - /// secondaryStylusButton, etc). For example, if this has the value 6 and the - /// [kind] is [PointerDeviceKind.invertedStylus], then this indicates an - /// upside-down stylus with both its primary and secondary buttons pressed. final int buttons; - - /// Set if an application from a different security domain is in any way - /// obscuring this application's window. (Aspirational; not currently - /// implemented.) final bool obscured; - - /// Set if this pointer data was synthesized by pointer data packet converter. - /// pointer data packet converter will synthesize additional pointer datas if - /// the input sequence of pointer data is illegal. - /// - /// For example, a down pointer data will be synthesized if the converter receives - /// a move pointer data while the pointer is not previously down. final bool synthesized; - - /// The pressure of the touch as a number ranging from 0.0, indicating a touch - /// with no discernible pressure, to 1.0, indicating a touch with "normal" - /// pressure, and possibly beyond, indicating a stronger touch. For devices - /// that do not detect pressure (e.g. mice), returns 1.0. final double pressure; - - /// The minimum value that [pressure] can return for this pointer. For devices - /// that do not detect pressure (e.g. mice), returns 1.0. This will always be - /// a number less than or equal to 1.0. final double pressureMin; - - /// The maximum value that [pressure] can return for this pointer. For devices - /// that do not detect pressure (e.g. mice), returns 1.0. This will always be - /// a greater than or equal to 1.0. final double pressureMax; - - /// The distance of the detected object from the input surface (e.g. the - /// distance of a stylus or finger from a touch screen), in arbitrary units on - /// an arbitrary (not necessarily linear) scale. If the pointer is down, this - /// is 0.0 by definition. final double distance; - - /// The maximum value that a distance can return for this pointer. If this - /// input device cannot detect "hover touch" input events, then this will be - /// 0.0. final double distanceMax; - - /// The area of the screen being pressed, scaled to a value between 0 and 1. - /// The value of size can be used to determine fat touch events. This value - /// is only set on Android, and is a device specific approximation within - /// the range of detectable values. So, for example, the value of 0.1 could - /// mean a touch with the tip of the finger, 0.2 a touch with full finger, - /// and 0.3 the full palm. final double size; - - /// The radius of the contact ellipse along the major axis, in logical pixels. final double radiusMajor; - - /// The radius of the contact ellipse along the minor axis, in logical pixels. final double radiusMinor; - - /// The minimum value that could be reported for radiusMajor and radiusMinor - /// for this pointer, in logical pixels. final double radiusMin; - - /// The minimum value that could be reported for radiusMajor and radiusMinor - /// for this pointer, in logical pixels. final double radiusMax; - - /// For PointerDeviceKind.touch events: - /// - /// The angle of the contact ellipse, in radius in the range: - /// - /// -pi/2 < orientation <= pi/2 - /// - /// ...giving the angle of the major axis of the ellipse with the y-axis - /// (negative angles indicating an orientation along the top-left / - /// bottom-right diagonal, positive angles indicating an orientation along the - /// top-right / bottom-left diagonal, and zero indicating an orientation - /// parallel with the y-axis). - /// - /// For PointerDeviceKind.stylus and PointerDeviceKind.invertedStylus events: - /// - /// The angle of the stylus, in radians in the range: - /// - /// -pi < orientation <= pi - /// - /// ...giving the angle of the axis of the stylus projected onto the input - /// surface, relative to the positive y-axis of that surface (thus 0.0 - /// indicates the stylus, if projected onto that surface, would go from the - /// contact point vertically up in the positive y-axis direction, pi would - /// indicate that the stylus would go down in the negative y-axis direction; - /// pi/4 would indicate that the stylus goes up and to the right, -pi/2 would - /// indicate that the stylus goes to the left, etc). final double orientation; - - /// For PointerDeviceKind.stylus and PointerDeviceKind.invertedStylus events: - /// - /// The angle of the stylus, in radians in the range: - /// - /// 0 <= tilt <= pi/2 - /// - /// ...giving the angle of the axis of the stylus, relative to the axis - /// perpendicular to the input surface (thus 0.0 indicates the stylus is - /// orthogonal to the plane of the input surface, while pi/2 indicates that - /// the stylus is flat on that surface). final double tilt; - - /// Opaque platform-specific data associated with the event. final int platformData; - - /// For events with signalKind of PointerSignalKind.scroll: - /// - /// The amount to scroll in the x direction, in physical pixels. final double scrollDeltaX; - - /// For events with signalKind of PointerSignalKind.scroll: - /// - /// The amount to scroll in the y direction, in physical pixels. final double scrollDeltaY; @override String toString() => 'PointerData(x: $physicalX, y: $physicalY)'; - - /// Returns a complete textual description of the information in this object. String toStringFull() { return '$runtimeType(' - 'embedderId: $embedderId, ' - 'timeStamp: $timeStamp, ' - 'change: $change, ' - 'kind: $kind, ' - 'signalKind: $signalKind, ' - 'device: $device, ' - 'pointerIdentifier: $pointerIdentifier, ' - 'physicalX: $physicalX, ' - 'physicalY: $physicalY, ' - 'physicalDeltaX: $physicalDeltaX, ' - 'physicalDeltaY: $physicalDeltaY, ' - 'buttons: $buttons, ' - 'synthesized: $synthesized, ' - 'pressure: $pressure, ' - 'pressureMin: $pressureMin, ' - 'pressureMax: $pressureMax, ' - 'distance: $distance, ' - 'distanceMax: $distanceMax, ' - 'size: $size, ' - 'radiusMajor: $radiusMajor, ' - 'radiusMinor: $radiusMinor, ' - 'radiusMin: $radiusMin, ' - 'radiusMax: $radiusMax, ' - 'orientation: $orientation, ' - 'tilt: $tilt, ' - 'platformData: $platformData, ' - 'scrollDeltaX: $scrollDeltaX, ' - 'scrollDeltaY: $scrollDeltaY' + 'embedderId: $embedderId, ' + 'timeStamp: $timeStamp, ' + 'change: $change, ' + 'kind: $kind, ' + 'signalKind: $signalKind, ' + 'device: $device, ' + 'pointerIdentifier: $pointerIdentifier, ' + 'physicalX: $physicalX, ' + 'physicalY: $physicalY, ' + 'physicalDeltaX: $physicalDeltaX, ' + 'physicalDeltaY: $physicalDeltaY, ' + 'buttons: $buttons, ' + 'synthesized: $synthesized, ' + 'pressure: $pressure, ' + 'pressureMin: $pressureMin, ' + 'pressureMax: $pressureMax, ' + 'distance: $distance, ' + 'distanceMax: $distanceMax, ' + 'size: $size, ' + 'radiusMajor: $radiusMajor, ' + 'radiusMinor: $radiusMinor, ' + 'radiusMin: $radiusMin, ' + 'radiusMax: $radiusMax, ' + 'orientation: $orientation, ' + 'tilt: $tilt, ' + 'platformData: $platformData, ' + 'scrollDeltaX: $scrollDeltaX, ' + 'scrollDeltaY: $scrollDeltaY' ')'; } } -/// A sequence of reports about the state of pointers. class PointerDataPacket { - /// Creates a packet of pointer data reports. - const PointerDataPacket({ this.data = const [] }) : assert(data != null); // ignore: unnecessary_null_comparison - - /// Data about the individual pointers in this packet. - /// - /// This list might contain multiple pieces of data about the same pointer. + const PointerDataPacket({this.data = const []}) + : assert(data != null); // ignore: unnecessary_null_comparison final List data; } diff --git a/engine/src/flutter/lib/web_ui/lib/src/ui/semantics.dart b/engine/src/flutter/lib/web_ui/lib/src/ui/semantics.dart index a0fde9a5b7..24b0acc4f3 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/ui/semantics.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/ui/semantics.dart @@ -5,8 +5,6 @@ // @dart = 2.10 part of ui; -/// The possible actions that can be conveyed from the operating system -/// accessibility APIs to a semantics node. class SemanticsAction { const SemanticsAction._(this.index) : assert(index != null); // ignore: unnecessary_null_comparison @@ -31,172 +29,34 @@ class SemanticsAction { static const int _kDismissIndex = 1 << 18; static const int _kMoveCursorForwardByWordIndex = 1 << 19; static const int _kMoveCursorBackwardByWordIndex = 1 << 20; - - /// The numerical value for this action. - /// - /// Each action has one bit set in this bit field. final int index; - - /// The equivalent of a user briefly tapping the screen with the finger - /// without moving it. static const SemanticsAction tap = SemanticsAction._(_kTapIndex); - - /// The equivalent of a user pressing and holding the screen with the finger - /// for a few seconds without moving it. static const SemanticsAction longPress = SemanticsAction._(_kLongPressIndex); - - /// The equivalent of a user moving their finger across the screen from right - /// to left. - /// - /// This action should be recognized by controls that are horizontally - /// scrollable. - static const SemanticsAction scrollLeft = - SemanticsAction._(_kScrollLeftIndex); - - /// The equivalent of a user moving their finger across the screen from left - /// to right. - /// - /// This action should be recognized by controls that are horizontally - /// scrollable. - static const SemanticsAction scrollRight = - SemanticsAction._(_kScrollRightIndex); - - /// The equivalent of a user moving their finger across the screen from - /// bottom to top. - /// - /// This action should be recognized by controls that are vertically - /// scrollable. + static const SemanticsAction scrollLeft = SemanticsAction._(_kScrollLeftIndex); + static const SemanticsAction scrollRight = SemanticsAction._(_kScrollRightIndex); static const SemanticsAction scrollUp = SemanticsAction._(_kScrollUpIndex); - - /// The equivalent of a user moving their finger across the screen from top - /// to bottom. - /// - /// This action should be recognized by controls that are vertically - /// scrollable. - static const SemanticsAction scrollDown = - SemanticsAction._(_kScrollDownIndex); - - /// A request to increase the value represented by the semantics node. - /// - /// For example, this action might be recognized by a slider control. + static const SemanticsAction scrollDown = SemanticsAction._(_kScrollDownIndex); static const SemanticsAction increase = SemanticsAction._(_kIncreaseIndex); - - /// A request to decrease the value represented by the semantics node. - /// - /// For example, this action might be recognized by a slider control. static const SemanticsAction decrease = SemanticsAction._(_kDecreaseIndex); - - /// A request to fully show the semantics node on screen. - /// - /// For example, this action might be send to a node in a scrollable list that - /// is partially off screen to bring it on screen. - static const SemanticsAction showOnScreen = - SemanticsAction._(_kShowOnScreenIndex); - - /// Move the cursor forward by one character. - /// - /// This is for example used by the cursor control in text fields. - /// - /// The action includes a boolean argument, which indicates whether the cursor - /// movement should extend (or start) a selection. + static const SemanticsAction showOnScreen = SemanticsAction._(_kShowOnScreenIndex); static const SemanticsAction moveCursorForwardByCharacter = SemanticsAction._(_kMoveCursorForwardByCharacterIndex); - - /// Move the cursor backward by one character. - /// - /// This is for example used by the cursor control in text fields. - /// - /// The action includes a boolean argument, which indicates whether the cursor - /// movement should extend (or start) a selection. static const SemanticsAction moveCursorBackwardByCharacter = SemanticsAction._(_kMoveCursorBackwardByCharacterIndex); - - /// Set the text selection to the given range. - /// - /// The provided argument is a Map which includes the keys `base` - /// and `extent` indicating where the selection within the `value` of the - /// semantics node should start and where it should end. Values for both - /// keys can range from 0 to length of `value` (inclusive). - /// - /// Setting `base` and `extent` to the same value will move the cursor to - /// that position (without selecting anything). - static const SemanticsAction setSelection = - SemanticsAction._(_kSetSelectionIndex); - - /// Copy the current selection to the clipboard. + static const SemanticsAction setSelection = SemanticsAction._(_kSetSelectionIndex); static const SemanticsAction copy = SemanticsAction._(_kCopyIndex); - - /// Cut the current selection and place it in the clipboard. static const SemanticsAction cut = SemanticsAction._(_kCutIndex); - - /// Paste the current content of the clipboard. static const SemanticsAction paste = SemanticsAction._(_kPasteIndex); - - /// Indicates that the nodes has gained accessibility focus. - /// - /// This handler is invoked when the node annotated with this handler gains - /// the accessibility focus. The accessibility focus is the - /// green (on Android with TalkBack) or black (on iOS with VoiceOver) - /// rectangle shown on screen to indicate what element an accessibility - /// user is currently interacting with. - /// - /// The accessibility focus is different from the input focus. The input focus - /// is usually held by the element that currently responds to keyboard inputs. - /// Accessibility focus and input focus can be held by two different nodes! static const SemanticsAction didGainAccessibilityFocus = SemanticsAction._(_kDidGainAccessibilityFocusIndex); - - /// Indicates that the nodes has lost accessibility focus. - /// - /// This handler is invoked when the node annotated with this handler - /// loses the accessibility focus. The accessibility focus is - /// the green (on Android with TalkBack) or black (on iOS with VoiceOver) - /// rectangle shown on screen to indicate what element an accessibility - /// user is currently interacting with. - /// - /// The accessibility focus is different from the input focus. The input focus - /// is usually held by the element that currently responds to keyboard inputs. - /// Accessibility focus and input focus can be held by two different nodes! static const SemanticsAction didLoseAccessibilityFocus = SemanticsAction._(_kDidLoseAccessibilityFocusIndex); - - /// Indicates that the user has invoked a custom accessibility action. - /// - /// This handler is added automatically whenever a custom accessibility - /// action is added to a semantics node. static const SemanticsAction customAction = SemanticsAction._(_kCustomAction); - - /// A request that the node should be dismissed. - /// - /// A [Snackbar], for example, may have a dismiss action to indicate to the - /// user that it can be removed after it is no longer relevant. On Android, - /// (with TalkBack) special hint text is spoken when focusing the node and - /// a custom action is availible in the local context menu. On iOS, - /// (with VoiceOver) users can perform a standard gesture to dismiss it. static const SemanticsAction dismiss = SemanticsAction._(_kDismissIndex); - - /// Move the cursor forward by one word. - /// - /// This is for example used by the cursor control in text fields. - /// - /// The action includes a boolean argument, which indicates whether the cursor - /// movement should extend (or start) a selection. static const SemanticsAction moveCursorForwardByWord = SemanticsAction._(_kMoveCursorForwardByWordIndex); - - /// Move the cursor backward by one word. - /// - /// This is for example used by the cursor control in text fields. - /// - /// The action includes a boolean argument, which indicates whether the cursor - /// movement should extend (or start) a selection. static const SemanticsAction moveCursorBackwardByWord = SemanticsAction._(_kMoveCursorBackwardByWordIndex); - - /// The possible semantics actions. - /// - /// The map's key is the [index] of the action and the value is the action - /// itself. static const Map values = { _kTapIndex: tap, _kLongPressIndex: longPress, @@ -272,7 +132,6 @@ class SemanticsAction { } } -/// A Boolean value that can be associated with a semantics node. class SemanticsFlag { static const int _kHasCheckedStateIndex = 1 << 0; static const int _kIsCheckedIndex = 1 << 1; @@ -299,233 +158,30 @@ class SemanticsFlag { static const int _kIsLinkIndex = 1 << 22; const SemanticsFlag._(this.index) : assert(index != null); // ignore: unnecessary_null_comparison - - /// The numerical value for this flag. - /// - /// Each flag has one bit set in this bit field. final int index; - - /// The semantics node has the quality of either being "checked" or "unchecked". - /// - /// This flag is mutually exclusive with [hasToggledState]. - /// - /// For example, a checkbox or a radio button widget has checked state. - /// - /// See also: - /// - /// * [SemanticsFlag.isChecked], which controls whether the node is "checked" or "unchecked". - static const SemanticsFlag hasCheckedState = - SemanticsFlag._(_kHasCheckedStateIndex); - - /// Whether a semantics node that [hasCheckedState] is checked. - /// - /// If true, the semantics node is "checked". If false, the semantics node is - /// "unchecked". - /// - /// For example, if a checkbox has a visible checkmark, [isChecked] is true. - /// - /// See also: - /// - /// * [SemanticsFlag.hasCheckedState], which enables a checked state. + static const SemanticsFlag hasCheckedState = SemanticsFlag._(_kHasCheckedStateIndex); static const SemanticsFlag isChecked = SemanticsFlag._(_kIsCheckedIndex); - - /// Whether a semantics node is selected. - /// - /// If true, the semantics node is "selected". If false, the semantics node is - /// "unselected". - /// - /// For example, the active tab in a tab bar has [isSelected] set to true. static const SemanticsFlag isSelected = SemanticsFlag._(_kIsSelectedIndex); - - /// Whether the semantic node represents a button. - /// - /// Platforms has special handling for buttons, for example Android's TalkBack - /// and iOS's VoiceOver provides an additional hint when the focused object is - /// a button. static const SemanticsFlag isButton = SemanticsFlag._(_kIsButtonIndex); - - /// Whether the semantic node represents a link. - /// - /// Platforms have special handling for links, for example, iOS's VoiceOver - /// provides an additional hint when the focused object is a link. static const SemanticsFlag isLink = SemanticsFlag._(_kIsLinkIndex); - - /// Whether the semantic node represents a text field. - /// - /// Text fields are announced as such and allow text input via accessibility - /// affordances. static const SemanticsFlag isTextField = SemanticsFlag._(_kIsTextFieldIndex); - - /// Whether the semantic node is read only. - /// - /// Only applicable when [isTextField] is true. static const SemanticsFlag isReadOnly = SemanticsFlag._(_kIsReadOnlyIndex); - - /// Whether the semantic node is able to hold the user's focus. - /// - /// The focused element is usually the current receiver of keyboard inputs. static const SemanticsFlag isFocusable = SemanticsFlag._(_kIsFocusableIndex); - - /// Whether the semantic node currently holds the user's focus. - /// - /// The focused element is usually the current receiver of keyboard inputs. static const SemanticsFlag isFocused = SemanticsFlag._(_kIsFocusedIndex); - - /// The semantics node has the quality of either being "enabled" or - /// "disabled". - /// - /// For example, a button can be enabled or disabled and therefore has an - /// "enabled" state. Static text is usually neither enabled nor disabled and - /// therefore does not have an "enabled" state. - static const SemanticsFlag hasEnabledState = - SemanticsFlag._(_kHasEnabledStateIndex); - - /// Whether a semantic node that [hasEnabledState] is currently enabled. - /// - /// A disabled element does not respond to user interaction. For example, a - /// button that currently does not respond to user interaction should be - /// marked as disabled. + static const SemanticsFlag hasEnabledState = SemanticsFlag._(_kHasEnabledStateIndex); static const SemanticsFlag isEnabled = SemanticsFlag._(_kIsEnabledIndex); - - /// Whether a semantic node is in a mutually exclusive group. - /// - /// For example, a radio button is in a mutually exclusive group because - /// only one radio button in that group can be marked as [isChecked]. - static const SemanticsFlag isInMutuallyExclusiveGroup = - SemanticsFlag._(_kIsInMutuallyExclusiveGroupIndex); - - /// Whether a semantic node is a header that divides content into sections. - /// - /// For example, headers can be used to divide a list of alphabetically - /// sorted words into the sections A, B, C, etc. as can be found in many - /// address book applications. + static const SemanticsFlag isInMutuallyExclusiveGroup = SemanticsFlag._(_kIsInMutuallyExclusiveGroupIndex); static const SemanticsFlag isHeader = SemanticsFlag._(_kIsHeaderIndex); - - /// Whether the value of the semantics node is obscured. - /// - /// This is usually used for text fields to indicate that its content - /// is a password or contains other sensitive information. static const SemanticsFlag isObscured = SemanticsFlag._(_kIsObscuredIndex); - - /// Whether the semantics node is the root of a subtree for which a route name - /// should be announced. - /// - /// When a node with this flag is removed from the semantics tree, the - /// framework will select the last in depth-first, paint order node with this - /// flag. When a node with this flag is added to the semantics tree, it is - /// selected automatically, unless there were multiple nodes with this flag - /// added. In this case, the last added node in depth-first, paint order - /// will be selected. - /// - /// From this selected node, the framework will search in depth-first, paint - /// order for the first node with a [namesRoute] flag and a non-null, - /// non-empty label. The [namesRoute] and [scopesRoute] flags may be on the - /// same node. The label of the found node will be announced as an edge - /// transition. If no non-empty, non-null label is found then: - /// - /// * VoiceOver will make a chime announcement. - /// * TalkBack will make no announcement - /// - /// Semantic nodes annotated with this flag are generally not a11y focusable. - /// - /// This is used in widgets such as Routes, Drawers, and Dialogs to - /// communicate significant changes in the visible screen. static const SemanticsFlag scopesRoute = SemanticsFlag._(_kScopesRouteIndex); - - /// Whether the semantics node label is the name of a visually distinct - /// route. - /// - /// This is used by certain widgets like Drawers and Dialogs, to indicate - /// that the node's semantic label can be used to announce an edge triggered - /// semantics update. - /// - /// Semantic nodes annotated with this flag will still recieve a11y focus. - /// - /// Updating this label within the same active route subtree will not cause - /// additional announcements. static const SemanticsFlag namesRoute = SemanticsFlag._(_kNamesRouteIndex); - - /// Whether the semantics node is considered hidden. - /// - /// Hidden elements are currently not visible on screen. They may be covered - /// by other elements or positioned outside of the visible area of a viewport. - /// - /// Hidden elements cannot gain accessibility focus though regular touch. The - /// only way they can be focused is by moving the focus to them via linear - /// navigation. - /// - /// Platforms are free to completely ignore hidden elements and new platforms - /// are encouraged to do so. - /// - /// Instead of marking an element as hidden it should usually be excluded from - /// the semantics tree altogether. Hidden elements are only included in the - /// semantics tree to work around platform limitations and they are mainly - /// used to implement accessibility scrolling on iOS. static const SemanticsFlag isHidden = SemanticsFlag._(_kIsHiddenIndex); - - /// Whether the semantics node represents an image. - /// - /// Both TalkBack and VoiceOver will inform the user the semantics node - /// represents an image. static const SemanticsFlag isImage = SemanticsFlag._(_kIsImageIndex); - - /// Whether the semantics node is a live region. - /// - /// A live region indicates that updates to semantics node are important. - /// Platforms may use this information to make polite announcements to the - /// user to inform them of updates to this node. - /// - /// An example of a live region is a [SnackBar] widget. On Android, A live - /// region causes a polite announcement to be generated automatically, even - /// if the user does not have focus of the widget. - static const SemanticsFlag isLiveRegion = - SemanticsFlag._(_kIsLiveRegionIndex); - - /// The semantics node has the quality of either being "on" or "off". - /// - /// This flag is mutually exclusive with [hasCheckedState]. - /// - /// For example, a switch has toggled state. - /// - /// See also: - /// - /// * [SemanticsFlag.isToggled], which controls whether the node is "on" or "off". - static const SemanticsFlag hasToggledState = - SemanticsFlag._(_kHasToggledStateIndex); - - /// If true, the semantics node is "on". If false, the semantics node is - /// "off". - /// - /// For example, if a switch is in the on position, [isToggled] is true. - /// - /// See also: - /// - /// * [SemanticsFlag.hasToggledState], which enables a toggled state. + static const SemanticsFlag isLiveRegion = SemanticsFlag._(_kIsLiveRegionIndex); + static const SemanticsFlag hasToggledState = SemanticsFlag._(_kHasToggledStateIndex); static const SemanticsFlag isToggled = SemanticsFlag._(_kIsToggledIndex); - - /// Whether the platform can scroll the semantics node when the user attempts - /// to move focus to an offscreen child. - /// - /// For example, a [ListView] widget has implicit scrolling so that users can - /// easily move to the next visible set of children. A [TabBar] widget does - /// not have implicit scrolling, so that users can navigate into the tab - /// body when reaching the end of the tab bar. - static const SemanticsFlag hasImplicitScrolling = - SemanticsFlag._(_kHasImplicitScrollingIndex); - - /// Whether the value of the semantics node is coming from a multi-line text - /// field. - /// - /// This isused for text fields to distinguish single-line text field from - /// multi-line ones. + static const SemanticsFlag hasImplicitScrolling = SemanticsFlag._(_kHasImplicitScrollingIndex); static const SemanticsFlag isMultiline = SemanticsFlag._(_kIsMultilineIndex); - - /// The possible semantics flags. - /// - /// The map's key is the [index] of the flag and the value is the flag itself. - /// The possible semantics flags. - /// - /// The map's key is the [index] of the flag and the value is the flag itself. static const Map values = { _kHasCheckedStateIndex: hasCheckedState, _kIsCheckedIndex: isChecked, @@ -607,65 +263,10 @@ class SemanticsFlag { } } -/// An object that creates [SemanticsUpdate] objects. -/// -/// Once created, the [SemanticsUpdate] objects can be passed to -/// [Window.updateSemantics] to update the semantics conveyed to the user. class SemanticsUpdateBuilder { - /// Creates an empty [SemanticsUpdateBuilder] object. SemanticsUpdateBuilder(); - final List _nodeUpdates = - []; - - /// Update the information associated with the node with the given `id`. - /// - /// The semantics nodes form a tree, with the root of the tree always having - /// an id of zero. The `childrenInTraversalOrder` and `childrenInHitTestOrder` - /// are the ids of the nodes that are immediate children of this node. The - /// former enumerates children in traversal order, and the latter enumerates - /// the same children in the hit test order. The two lists must have the same - /// length and contain the same ids. They may only differ in the order the - /// ids are listed in. For more information about different child orders, see - /// [DebugSemanticsDumpOrder]. - /// - /// The system retains the nodes that are currently reachable from the root. - /// A given update need not contain information for nodes that do not change - /// in the update. If a node is not reachable from the root after an update, - /// the node will be discarded from the tree. - /// - /// The `flags` are a bit field of [SemanticsFlag]s that apply to this node. - /// - /// The `actions` are a bit field of [SemanticsAction]s that can be undertaken - /// by this node. If the user wishes to undertake one of these actions on this - /// node, the [Window.onSemanticsAction] will be called with `id` and one of - /// the possible [SemanticsAction]s. Because the semantics tree is maintained - /// asynchronously, the [Window.onSemanticsAction] callback might be called - /// with an action that is no longer possible. - /// - /// The `label` is a string that describes this node. The `value` property - /// describes the current value of the node as a string. The `increasedValue` - /// string will become the `value` string after a [SemanticsAction.increase] - /// action is performed. The `decreasedValue` string will become the `value` - /// string after a [SemanticsAction.decrease] action is performed. The `hint` - /// string describes what result an action performed on this node has. The - /// reading direction of all these strings is given by `textDirection`. - /// - /// The fields 'textSelectionBase' and 'textSelectionExtent' describe the - /// currently selected text within `value`. - /// - /// For scrollable nodes `scrollPosition` describes the current scroll - /// position in logical pixel. `scrollExtentMax` and `scrollExtentMin` - /// describe the maximum and minimum in-rage values that `scrollPosition` can - /// be. Both or either may be infinity to indicate unbound scrolling. The - /// value for `scrollPosition` can (temporarily) be outside this range, for - /// example during an overscroll. - /// - /// The `rect` is the region occupied by this node in its own coordinate - /// system. - /// - /// The `transform` is a matrix that maps this node's coordinate system into - /// its parent's coordinate system. + final List _nodeUpdates = []; void updateNode({ required int id, required int flags, @@ -726,16 +327,14 @@ class SemanticsUpdateBuilder { )); } - void updateCustomAction( - {required int id, String? label, String? hint, int overrideId = -1}) { + void updateCustomAction({ + required int id, + String? label, + String? hint, + int overrideId = -1, + }) { // TODO(yjbanov): implement. } - - /// Creates a [SemanticsUpdate] object that encapsulates the updates recorded - /// by this object. - /// - /// The returned object can be passed to [Window.updateSemantics] to actually - /// update the semantics retained by the system. SemanticsUpdate build() { return SemanticsUpdate._( nodeUpdates: _nodeUpdates, @@ -743,23 +342,8 @@ class SemanticsUpdateBuilder { } } -/// An opaque object representing a batch of semantics updates. -/// -/// To create a SemanticsUpdate object, use a [SemanticsUpdateBuilder]. -/// -/// Semantics updates can be applied to the system's retained semantics tree -/// using the [Window.updateSemantics] method. abstract class SemanticsUpdate { - /// This class is created by the engine, and should not be instantiated - /// or extended directly. - /// - /// To create a SemanticsUpdate object, use a [SemanticsUpdateBuilder]. factory SemanticsUpdate._({List? nodeUpdates}) = engine.SemanticsUpdate; - - /// Releases the resources used by this semantics update. - /// - /// After calling this function, the semantics update is cannot be used - /// further. void dispose(); } diff --git a/engine/src/flutter/lib/web_ui/lib/src/ui/test_embedding.dart b/engine/src/flutter/lib/web_ui/lib/src/ui/test_embedding.dart index 955dbfe53c..7007ebf442 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/ui/test_embedding.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/ui/test_embedding.dart @@ -7,30 +7,22 @@ // @dart = 2.10 part of ui; -/// Used to track when the platform is initialized. This ensures the test fonts -/// are available. Future? _testPlatformInitializedFuture; -/// If the platform is already initialized (by a previous test), then run the test -/// body immediately. Otherwise, initialize the platform then run the test. -Future ensureTestPlatformInitializedThenRunTest( - dynamic Function() body) { +Future ensureTestPlatformInitializedThenRunTest(dynamic Function() body) { if (_testPlatformInitializedFuture == null) { debugEmulateFlutterTesterEnvironment = true; // Initializing the platform will ensure that the test font is loaded. - _testPlatformInitializedFuture = webOnlyInitializePlatform( - assetManager: engine.WebOnlyMockAssetManager()); + _testPlatformInitializedFuture = + webOnlyInitializePlatform(assetManager: engine.WebOnlyMockAssetManager()); } return _testPlatformInitializedFuture!.then((_) => body()); } -/// Used to track when the platform is initialized. This ensures the test fonts -/// are available. // TODO(yjbanov): can we make this late non-null? See https://github.com/dart-lang/sdk/issues/42214 Future? _platformInitializedFuture; -/// Initializes domRenderer with specific devicePixelRatio and physicalSize. Future webOnlyInitializeTestDomRenderer({double devicePixelRatio = 3.0}) { // Force-initialize DomRenderer so it doesn't overwrite test pixel ratio. engine.domRenderer; diff --git a/engine/src/flutter/lib/web_ui/lib/src/ui/text.dart b/engine/src/flutter/lib/web_ui/lib/src/ui/text.dart index 58698d862a..054ac36a84 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/ui/text.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/ui/text.dart @@ -6,99 +6,34 @@ // @dart = 2.10 part of ui; -/// Whether to slant the glyphs in the font enum FontStyle { - /// Use the upright glyphs normal, - - /// Use glyphs designed for slanting italic, } -/// Where to vertically align the placeholder relative to the surrounding text. -/// -/// Used by [ParagraphBuilder.addPlaceholder]. enum PlaceholderAlignment { - /// Match the baseline of the placeholder with the baseline. - /// - /// The [TextBaseline] to use must be specified and non-null when using this - /// alignment mode. baseline, - - /// Align the bottom edge of the placeholder with the baseline such that the - /// placeholder sits on top of the baseline. - /// - /// The [TextBaseline] to use must be specified and non-null when using this - /// alignment mode. aboveBaseline, - - /// Align the top edge of the placeholder with the baseline specified - /// such that the placeholder hangs below the baseline. - /// - /// The [TextBaseline] to use must be specified and non-null when using this - /// alignment mode. belowBaseline, - - /// Align the top edge of the placeholder with the top edge of the font. - /// - /// When the placeholder is very tall, the extra space will hang from - /// the top and extend through the bottom of the line. top, - - /// Align the bottom edge of the placeholder with the top edge of the font. - /// - /// When the placeholder is very tall, the extra space will rise from the - /// bottom and extend through the top of the line. bottom, - - /// Align the middle of the placeholder with the middle of the text. - /// - /// When the placeholder is very tall, the extra space will grow equally - /// from the top and bottom of the line. middle, } -/// The thickness of the glyphs used to draw the text class FontWeight { const FontWeight._(this.index); - - /// The encoded integer value of this font weight. final int index; - - /// Thin, the least thick static const FontWeight w100 = FontWeight._(0); - - /// Extra-light static const FontWeight w200 = FontWeight._(1); - - /// Light static const FontWeight w300 = FontWeight._(2); - - /// Normal / regular / plain static const FontWeight w400 = FontWeight._(3); - - /// Medium static const FontWeight w500 = FontWeight._(4); - - /// Semi-bold static const FontWeight w600 = FontWeight._(5); - - /// Bold static const FontWeight w700 = FontWeight._(6); - - /// Extra-bold static const FontWeight w800 = FontWeight._(7); - - /// Black, the most thick static const FontWeight w900 = FontWeight._(8); - - /// The default font weight. static const FontWeight normal = w400; - - /// A commonly used font weight that is heavier than normal. static const FontWeight bold = w700; - - /// A list of all the font weights. static const List values = [ w100, w200, @@ -110,27 +45,6 @@ class FontWeight { w800, w900 ]; - - /// Linearly interpolates between two font weights. - /// - /// Rather than using fractional weights, the interpolation rounds to the - /// nearest weight. - /// - /// Any null values for `a` or `b` are interpreted as equivalent to [normal] - /// (also known as [w400]). - /// - /// The `t` argument represents position on the timeline, with 0.0 meaning - /// that the interpolation has not started, returning `a` (or something - /// equivalent to `a`), 1.0 meaning that the interpolation has finished, - /// returning `b` (or something equivalent to `b`), and values in between - /// meaning that the interpolation is at the relevant point on the timeline - /// between `a` and `b`. The interpolation can be extrapolated beyond 0.0 and - /// 1.0, so negative values and values greater than 1.0 are valid (and can - /// easily be generated by curves such as [Curves.elasticInOut]). The result - /// is clamped to the range [w100]–[w900]. - /// - /// Values for `t` are usually obtained from an [Animation], such as - /// an [AnimationController]. static FontWeight? lerp(FontWeight? a, FontWeight? b, double t) { assert(t != null); // ignore: unnecessary_null_comparison if (a == null && b == null) @@ -154,129 +68,35 @@ class FontWeight { } } -/// A feature tag and value that affect the selection of glyphs in a font. class FontFeature { - /// Creates a [FontFeature] object, which can be added to a [TextStyle] to - /// change how the engine selects glyphs when rendering text. - /// - /// `feature` is the four-character tag that identifies the feature. - /// These tags are specified by font formats such as OpenType. - /// - /// `value` is the value that the feature will be set to. The behavior - /// of the value depends on the specific feature. Many features are - /// flags whose value can be 1 (when enabled) or 0 (when disabled). - /// - /// See const FontFeature(this.feature, [this.value = 1]) : assert(feature != null), // ignore: unnecessary_null_comparison assert(feature.length == 4), assert(value != null), // ignore: unnecessary_null_comparison assert(value >= 0); - - /// Create a [FontFeature] object that enables the feature with the given tag. const FontFeature.enable(String feature) : this(feature, 1); - - /// Create a [FontFeature] object that disables the feature with the given tag. const FontFeature.disable(String feature) : this(feature, 0); - - /// Randomize the alternate forms used in text. - /// - /// For example, this can be used with suitably-prepared handwriting fonts to - /// vary the forms used for each character, so that, for instance, the word - /// "cross-section" would be rendered with two different "c"s, two different "o"s, - /// and three different "s"s. - /// - /// See also: - /// - /// * const FontFeature.randomize() : feature = 'rand', value = 1; - - /// Select a stylistic set. - /// - /// Fonts may have up to 20 stylistic sets, numbered 1 through 20. - /// - /// See also: - /// - /// * factory FontFeature.stylisticSet(int value) { assert(value >= 1); assert(value <= 20); return FontFeature('ss${value.toString().padLeft(2, "0")}'); } - - /// Use the slashed zero. - /// - /// Some fonts contain both a circular zero and a zero with a slash. This - /// enables the use of the latter form. - /// - /// This is overridden by [FontFeature.oldstyleFigures]. - /// - /// See also: - /// - /// * const FontFeature.slashedZero() : feature = 'zero', value = 1; - - /// Use oldstyle figures. - /// - /// Some fonts have variants of the figures (e.g. the digit 9) that, when - /// this feature is enabled, render with descenders under the baseline instead - /// of being entirely above the baseline. - /// - /// This overrides [FontFeature.slashedZero]. - /// - /// See also: - /// - /// * const FontFeature.oldstyleFigures() : feature = 'onum', value = 1; - - /// Use proportional (varying width) figures. - /// - /// For fonts that have both proportional and tabular (monospace) figures, - /// this enables the proportional figures. - /// - /// This is mutually exclusive with [FontFeature.tabularFigures]. - /// - /// The default behavior varies from font to font. - /// - /// See also: - /// - /// * const FontFeature.proportionalFigures() : feature = 'pnum', value = 1; - - /// Use tabular (monospace) figures. - /// - /// For fonts that have both proportional (varying width) and tabular figures, - /// this enables the tabular figures. - /// - /// This is mutually exclusive with [FontFeature.proportionalFigures]. - /// - /// The default behavior varies from font to font. - /// - /// See also: - /// - /// * const FontFeature.tabularFigures() : feature = 'tnum', value = 1; - - /// The tag that identifies the effect of this feature. Must consist of 4 - /// ASCII characters (typically lowercase letters). - /// - /// See final String feature; - - /// The value assigned to this feature. - /// - /// Must be a positive integer. Many features are Boolean values that accept - /// values of either 0 (feature is disabled) or 1 (feature is enabled). final int value; @override @@ -299,53 +119,23 @@ class FontFeature { String toString() => 'FontFeature($feature, $value)'; } -/// Whether and how to align text horizontally. // The order of this enum must match the order of the values in RenderStyleConstants.h's ETextAlign. enum TextAlign { - /// Align the text on the left edge of the container. left, - - /// Align the text on the right edge of the container. right, - - /// Align the text in the center of the container. center, - - /// Stretch lines of text that end with a soft line break to fill the width of - /// the container. - /// - /// Lines that end with hard line breaks are aligned towards the [start] edge. justify, - - /// Align the text on the leading edge of the container. - /// - /// For left-to-right text ([TextDirection.ltr]), this is the left edge. - /// - /// For right-to-left text ([TextDirection.rtl]), this is the right edge. start, - - /// Align the text on the trailing edge of the container. - /// - /// For left-to-right text ([TextDirection.ltr]), this is the right edge. - /// - /// For right-to-left text ([TextDirection.rtl]), this is the left edge. end, } -/// A horizontal line used for aligning text. enum TextBaseline { - /// The horizontal line used to align the bottom of glyphs for alphabetic characters. alphabetic, - - /// The horizontal line used to align ideographic characters. ideographic, } -/// A linear decoration to draw near the text. class TextDecoration { const TextDecoration._(this._mask); - - /// Creates a decoration that paints the union of all the given decorations. factory TextDecoration.combine(List decorations) { int mask = 0; for (TextDecoration decoration in decorations) { @@ -355,22 +145,13 @@ class TextDecoration { } final int _mask; - - /// Whether this decoration will paint at least as much decoration as the given decoration. bool contains(TextDecoration other) { return (_mask | other._mask) == _mask; } - /// Do not draw a decoration static const TextDecoration none = TextDecoration._(0x0); - - /// Draw a line underneath each line of text static const TextDecoration underline = TextDecoration._(0x1); - - /// Draw a line above each line of text static const TextDecoration overline = TextDecoration._(0x2); - - /// Draw a line through each line of text static const TextDecoration lineThrough = TextDecoration._(0x4); @override @@ -404,81 +185,24 @@ class TextDecoration { } } -/// The style in which to draw a text decoration enum TextDecorationStyle { - /// Draw a solid line solid, - - /// Draw two lines double, - - /// Draw a dotted line dotted, - - /// Draw a dashed line dashed, - - /// Draw a sinusoidal line wavy } -/// Defines how the paragraph will apply [TextStyle.height] the ascent of the -/// first line and descent of the last line. -/// -/// The boolean value represents whether the [TextStyle.height] modifier will -/// be applied to the corresponding metric. By default, all properties are true, -/// and [TextStyle.height] is applied as normal. When set to false, the font's -/// default ascent will be used. class TextHeightBehavior { - - /// Creates a new TextHeightBehavior object. - /// - /// * applyHeightToFirstAscent: When true, the [TextStyle.height] modifier - /// will be applied to the ascent of the first line. When false, the font's - /// default ascent will be used. - /// * applyHeightToLastDescent: When true, the [TextStyle.height] modifier - /// will be applied to the descent of the last line. When false, the font's - /// default descent will be used. - /// - /// All properties default to true (height modifications applied as normal). const TextHeightBehavior({ this.applyHeightToFirstAscent = true, this.applyHeightToLastDescent = true, }); - - /// Creates a new TextHeightBehavior object from an encoded form. - /// - /// See [encode] for the creation of the encoded form. const TextHeightBehavior.fromEncoded(int encoded) : applyHeightToFirstAscent = (encoded & 0x1) == 0, applyHeightToLastDescent = (encoded & 0x2) == 0; - - - /// Whether to apply the [TextStyle.height] modifier to the ascent of the first - /// line in the paragraph. - /// - /// When true, the [TextStyle.height] modifier will be applied to to the ascent - /// of the first line. When false, the font's default ascent will be used and - /// the [TextStyle.height] will have no effect on the ascent of the first line. - /// - /// This property only has effect if a non-null [TextStyle.height] is specified. - /// - /// Defaults to true (height modifications applied as normal). final bool applyHeightToFirstAscent; - - /// Whether to apply the [TextStyle.height] modifier to the descent of the last - /// line in the paragraph. - /// - /// When true, the [TextStyle.height] modifier will be applied to to the descent - /// of the last line. When false, the font's default descent will be used and - /// the [TextStyle.height] will have no effect on the descent of the last line. - /// - /// This property only has effect if a non-null [TextStyle.height] is specified. - /// - /// Defaults to true (height modifications applied as normal). final bool applyHeightToLastDescent; - - /// Returns an encoded int representation of this object. int encode() { return (applyHeightToFirstAscent ? 0 : 1 << 0) | (applyHeightToLastDescent ? 0 : 1 << 1); } @@ -486,7 +210,7 @@ class TextHeightBehavior { @override bool operator ==(Object other) { if (other.runtimeType != runtimeType) - return false; + return false; return other is TextHeightBehavior && other.applyHeightToFirstAscent == applyHeightToFirstAscent && other.applyHeightToLastDescent == applyHeightToLastDescent; @@ -509,33 +233,7 @@ class TextHeightBehavior { } } -/// An opaque object that determines the size, position, and rendering of text. abstract class TextStyle { - /// Creates a new TextStyle object. - /// - /// * `color`: The color to use when painting the text. If this is specified, `foreground` must be null. - /// * `decoration`: The decorations to paint near the text (e.g., an underline). - /// * `decorationColor`: The color in which to paint the text decorations. - /// * `decorationStyle`: The style in which to paint the text decorations (e.g., dashed). - /// * `fontWeight`: The typeface thickness to use when painting the text (e.g., bold). - /// * `fontStyle`: The typeface variant to use when drawing the letters (e.g., italics). - /// * `fontFamily`: The name of the font to use when painting the text (e.g., Roboto). If a `fontFamilyFallback` is - /// provided and `fontFamily` is not, then the first font family in `fontFamilyFallback` will take the postion of - /// the preferred font family. When a higher priority font cannot be found or does not contain a glyph, a lower - /// priority font will be used. - /// * `fontFamilyFallback`: An ordered list of the names of the fonts to fallback on when a glyph cannot - /// be found in a higher priority font. When the `fontFamily` is null, the first font family in this list - /// is used as the preferred font. Internally, the 'fontFamily` is concatenated to the front of this list. - /// When no font family is provided through 'fontFamilyFallback' (null or empty) or `fontFamily`, then the - /// platform default font will be used. - /// * `fontSize`: The size of glyphs (in logical pixels) to use when painting the text. - /// * `letterSpacing`: The amount of space (in logical pixels) to add between each letter. - /// * `wordSpacing`: The amount of space (in logical pixels) to add at each sequence of white-space (i.e. between each word). - /// * `textBaseline`: The common baseline that should be aligned between this text span and its parent text span, or, for the root text spans, with the line box. - /// * `height`: The height of this text span, as a multiple of the font size. - /// * `locale`: The locale used to select region-specific glyphs. - /// * `background`: The paint drawn as a background for the text. - /// * `foreground`: The paint used to draw the text. If this is specified, `color` must be null. factory TextStyle({ Color? color, TextDecoration? decoration, @@ -559,109 +257,54 @@ abstract class TextStyle { }) { if (engine.experimentalUseSkia) { return engine.CkTextStyle( - color: color, - decoration: decoration, - decorationColor: decorationColor, - decorationStyle: decorationStyle, - decorationThickness: decorationThickness, - fontWeight: fontWeight, - fontStyle: fontStyle, - textBaseline: textBaseline, - fontFamily: fontFamily, - fontFamilyFallback: fontFamilyFallback, - fontSize: fontSize, - letterSpacing: letterSpacing, - wordSpacing: wordSpacing, - height: height, - locale: locale, - background: background as engine.CkPaint?, - foreground: foreground as engine.CkPaint?, - shadows: shadows, - fontFeatures: fontFeatures, + color: color, + decoration: decoration, + decorationColor: decorationColor, + decorationStyle: decorationStyle, + decorationThickness: decorationThickness, + fontWeight: fontWeight, + fontStyle: fontStyle, + textBaseline: textBaseline, + fontFamily: fontFamily, + fontFamilyFallback: fontFamilyFallback, + fontSize: fontSize, + letterSpacing: letterSpacing, + wordSpacing: wordSpacing, + height: height, + locale: locale, + background: background as engine.CkPaint?, + foreground: foreground as engine.CkPaint?, + shadows: shadows, + fontFeatures: fontFeatures, ); } else { return engine.EngineTextStyle( - color: color, - decoration: decoration, - decorationColor: decorationColor, - decorationStyle: decorationStyle, - decorationThickness: decorationThickness, - fontWeight: fontWeight, - fontStyle: fontStyle, - textBaseline: textBaseline, - fontFamily: fontFamily, - fontFamilyFallback: fontFamilyFallback, - fontSize: fontSize, - letterSpacing: letterSpacing, - wordSpacing: wordSpacing, - height: height, - locale: locale, - background: background, - foreground: foreground, - shadows: shadows, - fontFeatures: fontFeatures, + color: color, + decoration: decoration, + decorationColor: decorationColor, + decorationStyle: decorationStyle, + decorationThickness: decorationThickness, + fontWeight: fontWeight, + fontStyle: fontStyle, + textBaseline: textBaseline, + fontFamily: fontFamily, + fontFamilyFallback: fontFamilyFallback, + fontSize: fontSize, + letterSpacing: letterSpacing, + wordSpacing: wordSpacing, + height: height, + locale: locale, + background: background, + foreground: foreground, + shadows: shadows, + fontFeatures: fontFeatures, ); } } } -/// An opaque object that determines the configuration used by -/// [ParagraphBuilder] to position lines within a [Paragraph] of text. abstract class ParagraphStyle { - /// Creates a new ParagraphStyle object. - /// - /// * `textAlign`: The alignment of the text within the lines of the - /// paragraph. If the last line is ellipsized (see `ellipsis` below), the - /// alignment is applied to that line after it has been truncated but before - /// the ellipsis has been added. // See: https://github.com/flutter/flutter/issues/9819 - /// - /// * `textDirection`: The directionality of the text, left-to-right (e.g. - /// Norwegian) or right-to-left (e.g. Hebrew). This controls the overall - /// directionality of the paragraph, as well as the meaning of - /// [TextAlign.start] and [TextAlign.end] in the `textAlign` field. - /// - /// * `maxLines`: The maximum number of lines painted. Lines beyond this - /// number are silently dropped. For example, if `maxLines` is 1, then only - /// one line is rendered. If `maxLines` is null, but `ellipsis` is not null, - /// then lines after the first one that overflows the width constraints are - /// dropped. The width constraints are those set in the - /// [ParagraphConstraints] object passed to the [Paragraph.layout] method. - /// - /// * `fontFamily`: The name of the font to use when painting the text (e.g., - /// Roboto). - /// - /// * `fontSize`: The size of glyphs (in logical pixels) to use when painting - /// the text. - /// - /// * `height`: The minimum height of the line boxes, as a multiple of the - /// font size. The lines of the paragraph will be at least - /// `(height + leading) * fontSize` tall when fontSize - /// is not null. When fontSize is null, there is no minimum line height. Tall - /// glyphs due to baseline alignment or large [TextStyle.fontSize] may cause - /// the actual line height after layout to be taller than specified here. - /// [fontSize] must be provided for this property to take effect. - /// - /// * `fontWeight`: The typeface thickness to use when painting the text - /// (e.g., bold). - /// - /// * `fontStyle`: The typeface variant to use when drawing the letters (e.g., - /// italics). - /// - /// * `strutStyle`: The properties of the strut. Strut defines a set of minimum - /// vertical line height related metrics and can be used to obtain more - /// advanced line spacing behavior. - /// - /// * `ellipsis`: String used to ellipsize overflowing text. If `maxLines` is - /// not null, then the `ellipsis`, if any, is applied to the last rendered - /// line, if that line overflows the width constraints. If `maxLines` is - /// null, then the `ellipsis` is applied to the first line that overflows - /// the width constraints, and subsequent lines are dropped. The width - /// constraints are those set in the [ParagraphConstraints] object passed to - /// the [Paragraph.layout] method. The empty string and the null value are - /// considered equivalent and turn off this behavior. - /// - /// * `locale`: The locale used to select region-specific glyphs. factory ParagraphStyle({ TextAlign? textAlign, TextDirection? textDirection, @@ -711,41 +354,6 @@ abstract class ParagraphStyle { } abstract class StrutStyle { - /// Creates a new StrutStyle object. - /// - /// * `fontFamily`: The name of the font to use when painting the text (e.g., - /// Roboto). - /// - /// * `fontFamilyFallback`: An ordered list of font family names that will be searched for when - /// the font in `fontFamily` cannot be found. - /// - /// * `fontSize`: The size of glyphs (in logical pixels) to use when painting - /// the text. - /// - /// * `lineHeight`: The minimum height of the line boxes, as a multiple of the - /// font size. The lines of the paragraph will be at least - /// `(lineHeight + leading) * fontSize` tall when fontSize - /// is not null. When fontSize is null, there is no minimum line height. Tall - /// glyphs due to baseline alignment or large [TextStyle.fontSize] may cause - /// the actual line height after layout to be taller than specified here. - /// [fontSize] must be provided for this property to take effect. - /// - /// * `leading`: The minimum amount of leading between lines as a multiple of - /// the font size. [fontSize] must be provided for this property to take effect. - /// - /// * `fontWeight`: The typeface thickness to use when painting the text - /// (e.g., bold). - /// - /// * `fontStyle`: The typeface variant to use when drawing the letters (e.g., - /// italics). - /// - /// * `forceStrutHeight`: When true, the paragraph will force all lines to be exactly - /// `(lineHeight + leading) * fontSize` tall from baseline to baseline. - /// [TextStyle] is no longer able to influence the line height, and any tall - /// glyphs may overlap with lines above. If a [fontFamily] is specified, the - /// total ascent of the first line will be the min of the `Ascent + half-leading` - /// of the [fontFamily] and `(lineHeight + leading) * fontSize`. Otherwise, it - /// will be determined by the Ascent + half-leading of the first text. factory StrutStyle({ String? fontFamily, List? fontFamilyFallback, @@ -758,104 +366,13 @@ abstract class StrutStyle { }) = engine.EngineStrutStyle; } -/// A direction in which text flows. -/// -/// Some languages are written from the left to the right (for example, English, -/// Tamil, or Chinese), while others are written from the right to the left (for -/// example Aramaic, Hebrew, or Urdu). Some are also written in a mixture, for -/// example Arabic is mostly written right-to-left, with numerals written -/// left-to-right. -/// -/// The text direction must be provided to APIs that render text or lay out -/// boxes horizontally, so that they can determine which direction to start in: -/// either right-to-left, [TextDirection.rtl]; or left-to-right, -/// [TextDirection.ltr]. -/// -/// ## Design discussion -/// -/// Flutter is designed to address the needs of applications written in any of -/// the world's currently-used languages, whether they use a right-to-left or -/// left-to-right writing direction. Flutter does not support other writing -/// modes, such as vertical text or boustrophedon text, as these are rarely used -/// in computer programs. -/// -/// It is common when developing user interface frameworks to pick a default -/// text direction — typically left-to-right, the direction most familiar to the -/// engineers working on the framework — because this simplifies the development -/// of applications on the platform. Unfortunately, this frequently results in -/// the platform having unexpected left-to-right biases or assumptions, as -/// engineers will typically miss places where they need to support -/// right-to-left text. This then results in bugs that only manifest in -/// right-to-left environments. -/// -/// In an effort to minimize the extent to which Flutter experiences this -/// category of issues, the lowest levels of the Flutter framework do not have a -/// default text reading direction. Any time a reading direction is necessary, -/// for example when text is to be displayed, or when a -/// writing-direction-dependent value is to be interpreted, the reading -/// direction must be explicitly specified. Where possible, such as in `switch` -/// statements, the right-to-left case is listed first, to avoid the impression -/// that it is an afterthought. -/// -/// At the higher levels (specifically starting at the widgets library), an -/// ambient [Directionality] is introduced, which provides a default. Thus, for -/// instance, a [Text] widget in the scope of a [MaterialApp] widget does not -/// need to be given an explicit writing direction. The [Directionality.of] -/// static method can be used to obtain the ambient text direction for a -/// particular [BuildContext]. -/// -/// ### Known left-to-right biases in Flutter -/// -/// Despite the design intent described above, certain left-to-right biases have -/// nonetheless crept into Flutter's design. These include: -/// -/// * The [Canvas] origin is at the top left, and the x-axis increases in a -/// left-to-right direction. -/// -/// * The default localization in the widgets and material libraries is -/// American English, which is left-to-right. -/// -/// ### Visual properties vs directional properties -/// -/// Many classes in the Flutter framework are offered in two versions, a -/// visually-oriented variant, and a text-direction-dependent variant. For -/// example, [EdgeInsets] is described in terms of top, left, right, and bottom, -/// while [EdgeInsetsDirectional] is described in terms of top, start, end, and -/// bottom, where start and end correspond to right and left in right-to-left -/// text and left and right in left-to-right text. -/// -/// There are distinct use cases for each of these variants. -/// -/// Text-direction-dependent variants are useful when developing user interfaces -/// that should "flip" with the text direction. For example, a paragraph of text -/// in English will typically be left-aligned and a quote will be indented from -/// the left, while in Arabic it will be right-aligned and indented from the -/// right. Both of these cases are described by the direction-dependent -/// [TextAlign.start] and [EdgeInsetsDirectional.start]. -/// -/// In contrast, the visual variants are useful when the text direction is known -/// and not affected by the reading direction. For example, an application -/// giving driving directions might show a "turn left" arrow on the left and a -/// "turn right" arrow on the right — and would do so whether the application -/// was localized to French (left-to-right) or Hebrew (right-to-left). -/// -/// In practice, it is also expected that many developers will only be -/// targeting one language, and in that case it may be simpler to think in -/// visual terms. // The order of this enum must match the order of the values in TextDirection.h's TextDirection. enum TextDirection { - /// The text flows from right to left (e.g. Arabic, Hebrew). rtl, - - /// The text flows from left to right (e.g., English, French). ltr, } -/// A rectangle enclosing a run of text. -/// -/// This is similar to [Rect] but includes an inherent [TextDirection]. class TextBox { - /// Creates an object that describes a box containing text. const TextBox.fromLTRBD( this.left, this.top, @@ -863,43 +380,16 @@ class TextBox { this.bottom, this.direction, ); - - /// The left edge of the text box, irrespective of direction. - /// - /// To get the leading edge (which may depend on the [direction]), consider [start]. final double left; - - /// The top edge of the text box. final double top; - - /// The right edge of the text box, irrespective of direction. - /// - /// To get the trailing edge (which may depend on the [direction]), consider [end]. final double right; - - /// The bottom edge of the text box. final double bottom; - - /// The direction in which text inside this box flows. final TextDirection direction; - - /// Returns a rect of the same size as this box. Rect toRect() => Rect.fromLTRB(left, top, right, bottom); - - /// The [left] edge of the box for left-to-right text; the [right] edge of the box for right-to-left text. - /// - /// See also: - /// - /// * [direction], which specifies the text direction. double get start { return (direction == TextDirection.ltr) ? left : right; } - /// The [right] edge of the box for left-to-right text; the [left] edge of the box for right-to-left text. - /// - /// See also: - /// - /// * [direction], which specifies the text direction. double get end { return (direction == TextDirection.ltr) ? right : left; } @@ -929,95 +419,18 @@ class TextBox { } } -/// A way to disambiguate a [TextPosition] when its offset could match two -/// different locations in the rendered string. -/// -/// For example, at an offset where the rendered text wraps, there are two -/// visual positions that the offset could represent: one prior to the line -/// break (at the end of the first line) and one after the line break (at the -/// start of the second line). A text affinity disambiguates between these two -/// cases. -/// -/// This affects only line breaks caused by wrapping, not explicit newline -/// characters. For newline characters, the position is fully specified by the -/// offset alone, and there is no ambiguity. -/// -/// [TextAffinity] also affects bidirectional text at the interface between LTR -/// and RTL text. Consider the following string, where the lowercase letters -/// will be displayed as LTR and the uppercase letters RTL: "helloHELLO". When -/// rendered, the string would appear visually as "helloOLLEH". An offset of 5 -/// would be ambiguous without a corresponding [TextAffinity]. Looking at the -/// string in code, the offset represents the position just after the "o" and -/// just before the "H". When rendered, this offset could be either in the -/// middle of the string to the right of the "o" or at the end of the string to -/// the right of the "H". enum TextAffinity { - /// The position has affinity for the upstream side of the text position, i.e. - /// in the direction of the beginning of the string. - /// - /// In the example of an offset at the place where text is wrapping, upstream - /// indicates the end of the first line. - /// - /// In the bidirectional text example "helloHELLO", an offset of 5 with - /// [TextAffinity] upstream would appear in the middle of the rendered text, - /// just to the right of the "o". See the definition of [TextAffinity] for the - /// full example. upstream, - - /// The position has affinity for the downstream side of the text position, - /// i.e. in the direction of the end of the string. - /// - /// In the example of an offset at the place where text is wrapping, - /// downstream indicates the beginning of the second line. - /// - /// In the bidirectional text example "helloHELLO", an offset of 5 with - /// [TextAffinity] downstream would appear at the end of the rendered text, - /// just to the right of the "H". See the definition of [TextAffinity] for the - /// full example. downstream, } -/// A position in a string of text. -/// -/// A TextPosition can be used to locate a position in a string in code (using -/// the [offset] property), and it can also be used to locate the same position -/// visually in a rendered string of text (using [offset] and, when needed to -/// resolve ambiguity, [affinity]). -/// -/// The location of an offset in a rendered string is ambiguous in two cases. -/// One happens when rendered text is forced to wrap. In this case, the offset -/// where the wrap occurs could visually appear either at the end of the first -/// line or the beginning of the second line. The second way is with -/// bidirectional text. An offset at the interface between two different text -/// directions could have one of two locations in the rendered text. -/// -/// See the documentation for [TextAffinity] for more information on how -/// TextAffinity disambiguates situations like these. class TextPosition { - /// Creates an object representing a particular position in a string. - /// - /// The arguments must not be null (so the [offset] argument is required). const TextPosition({ required this.offset, this.affinity = TextAffinity.downstream, }) : assert(offset != null), // ignore: unnecessary_null_comparison assert(affinity != null); // ignore: unnecessary_null_comparison - - /// The index of the character that immediately follows the position in the - /// string representation of the text. - /// - /// For example, given the string `'Hello'`, offset 0 represents the cursor - /// being before the `H`, while offset 5 represents the cursor being just - /// after the `o`. final int offset; - - /// Disambiguates cases where the position in the string given by [offset] - /// could represent two different visual positions in the rendered text. For - /// example, this can happen when text is forced to wrap, or when one string - /// of text is rendered with multiple text directions. - /// - /// See the documentation for [TextAffinity] for more information on how - /// TextAffinity disambiguates situations like these. final TextAffinity affinity; @override @@ -1039,64 +452,32 @@ class TextPosition { } } -/// A range of characters in a string of text. class TextRange { - /// Creates a text range. - /// - /// The [start] and [end] arguments must not be null. Both the [start] and - /// [end] must either be greater than or equal to zero or both exactly -1. - /// - /// Instead of creating an empty text range, consider using the [empty] - /// constant. const TextRange({ required this.start, required this.end, }) : assert(start != null && start >= -1), // ignore: unnecessary_null_comparison assert(end != null && end >= -1); // ignore: unnecessary_null_comparison - - /// A text range that starts and ends at offset. - /// - /// The [offset] argument must be non-null and greater than or equal to -1. const TextRange.collapsed(int offset) : assert(offset != null && offset >= -1), // ignore: unnecessary_null_comparison start = offset, end = offset; - - /// A text range that contains nothing and is not in the text. static const TextRange empty = TextRange(start: -1, end: -1); - - /// The index of the first character in the range. - /// - /// If [start] and [end] are both -1, the text range is empty. final int start; - - /// The next index after the characters in this range. - /// - /// If [start] and [end] are both -1, the text range is empty. final int end; - - /// Whether this range represents a valid position in the text. bool get isValid => start >= 0 && end >= 0; - - /// Whether this range is empty (but still potentially placed inside the text). bool get isCollapsed => start == end; - - /// Whether the start of this range precedes the end. bool get isNormalized => end >= start; - - /// The text before this range. String textBefore(String text) { assert(isNormalized); return text.substring(0, start); } - /// The text after this range. String textAfter(String text) { assert(isNormalized); return text.substring(end); } - /// The text inside this range. String textInside(String text) { assert(isNormalized); return text.substring(start, end); @@ -1122,37 +503,10 @@ class TextRange { String toString() => 'TextRange(start: $start, end: $end)'; } -/// Layout constraints for [Paragraph] objects. -/// -/// Instances of this class are typically used with [Paragraph.layout]. -/// -/// The only constraint that can be specified is the [width]. See the discussion -/// at [width] for more details. class ParagraphConstraints { - /// Creates constraints for laying out a pargraph. - /// - /// The [width] argument must not be null. const ParagraphConstraints({ required this.width, }) : assert(width != null); // ignore: unnecessary_null_comparison - - /// The width the paragraph should use whey computing the positions of glyphs. - /// - /// If possible, the paragraph will select a soft line break prior to reaching - /// this width. If no soft line break is available, the paragraph will select - /// a hard line break prior to reaching this width. If that would force a line - /// break without any characters having been placed (i.e. if the next - /// character to be laid out does not fit within the given width constraint) - /// then the next character is allowed to overflow the width constraint and a - /// forced line break is placed after it (even if an explicit line break - /// follows). - /// - /// The width influences how ellipses are applied. See the discussion at [new - /// ParagraphStyle] for more details. - /// - /// This width is also used to position glyphs according to the [TextAlign] - /// alignment described in the [ParagraphStyle] used when building the - /// [Paragraph] with a [ParagraphBuilder]. final double width; @override @@ -1171,72 +525,19 @@ class ParagraphConstraints { String toString() => '$runtimeType(width: $width)'; } -/// Defines various ways to vertically bound the boxes returned by -/// [Paragraph.getBoxesForRange]. enum BoxHeightStyle { - /// Provide tight bounding boxes that fit heights per run. This style may result - /// in uneven bounding boxes that do not nicely connect with adjacent boxes. tight, - - /// The height of the boxes will be the maximum height of all runs in the - /// line. All boxes in the same line will be the same height. This does not - /// guarantee that the boxes will cover the entire vertical height of the line - /// when there is additional line spacing. - /// - /// See [BoxHeightStyle.includeLineSpacingTop], [BoxHeightStyle.includeLineSpacingMiddle], - /// and [BoxHeightStyle.includeLineSpacingBottom] for styles that will cover - /// the entire line. max, - - /// Extends the top and bottom edge of the bounds to fully cover any line - /// spacing. - /// - /// The top and bottom of each box will cover half of the - /// space above and half of the space below the line. - /// - /// {@template flutter.dart:ui.boxHeightStyle.includeLineSpacing} - /// The top edge of each line should be the same as the bottom edge - /// of the line above. There should be no gaps in vertical coverage given any - /// amount of line spacing. Line spacing is not included above the first line - /// and below the last line due to no additional space present there. - /// {@endtemplate} includeLineSpacingMiddle, - - /// Extends the top edge of the bounds to fully cover any line spacing. - /// - /// The line spacing will be added to the top of the box. - /// - /// {@macro flutter.dart:ui.boxHeightStyle.includeLineSpacing} includeLineSpacingTop, - - /// Extends the bottom edge of the bounds to fully cover any line spacing. - /// - /// The line spacing will be added to the bottom of the box. - /// - /// {@macro flutter.dart:ui.boxHeightStyle.includeLineSpacing} includeLineSpacingBottom, - - /// Calculate box heights based on the metrics of this paragraph's [StrutStyle]. - /// - /// Boxes based on the strut will have consistent heights throughout the - /// entire paragraph. The top edge of each line will align with the bottom - /// edge of the previous line. It is possible for glyphs to extend outside - /// these boxes. strut, } -/// Defines various ways to horizontally bound the boxes returned by -/// [Paragraph.getBoxesForRange]. enum BoxWidthStyle { // Provide tight bounding boxes that fit widths to the runs of each line // independently. tight, - - /// Adds up to two additional boxes as needed at the beginning and/or end - /// of each line so that the widths of the boxes in line are the same width - /// as the widest line in the paragraph. The additional boxes on each line - /// are only added when the relevant box at the relevant edge of that line - /// does not span the maximum width of the paragraph. max, } @@ -1252,237 +553,38 @@ abstract class LineMetrics { required double baseline, required int lineNumber, }) = engine.EngineLineMetrics; - - /// {@template dart.ui.LineMetrics.hardBreak} - /// True if this line ends with an explicit line break (e.g. '\n') or is the end - /// of the paragraph. False otherwise. - /// {@endtemplate} bool get hardBreak; - - /// {@template dart.ui.LineMetrics.ascent} - /// The rise from the [baseline] as calculated from the font and style for this line. - /// - /// This is the final computed ascent and can be impacted by the strut, height, scaling, - /// as well as outlying runs that are very tall. - /// - /// The [ascent] is provided as a positive value, even though it is typically defined - /// in fonts as negative. This is to ensure the signage of operations with these - /// metrics directly reflects the intended signage of the value. For example, - /// the y coordinate of the top edge of the line is `baseline - ascent`. - /// {@endtemplate} double get ascent; - - /// {@template dart.ui.LineMetrics.descent} - /// The drop from the [baseline] as calculated from the font and style for this line. - /// - /// This is the final computed ascent and can be impacted by the strut, height, scaling, - /// as well as outlying runs that are very tall. - /// - /// The y coordinate of the bottom edge of the line is `baseline + descent`. - /// {@endtemplate} double get descent; - - /// {@template dart.ui.LineMetrics.unscaledAscent} - /// The rise from the [baseline] as calculated from the font and style for this line - /// ignoring the [TextStyle.height]. - /// - /// The [unscaledAscent] is provided as a positive value, even though it is typically - /// defined in fonts as negative. This is to ensure the signage of operations with - /// these metrics directly reflects the intended signage of the value. - /// {@endtemplate} double get unscaledAscent; - - /// {@template dart.ui.LineMetrics.height} - /// Total height of the line from the top edge to the bottom edge. - /// - /// This is equivalent to `round(ascent + descent)`. This value is provided - /// separately due to rounding causing sub-pixel differences from the unrounded - /// values. - /// {@endtemplate} double get height; - - /// {@template dart.ui.LineMetrics.width} - /// Width of the line from the left edge of the leftmost glyph to the right - /// edge of the rightmost glyph. - /// - /// This is not the same as the width of the pargraph. - /// - /// See also: - /// - /// * [Paragraph.width], the max width passed in during layout. - /// * [Paragraph.longestLine], the width of the longest line in the paragraph. - /// {@endtemplate} double get width; - - /// {@template dart.ui.LineMetrics.left} - /// The x coordinate of left edge of the line. - /// - /// The right edge can be obtained with `left + width`. - /// {@endtemplate} double get left; - - /// {@template dart.ui.LineMetrics.baseline} - /// The y coordinate of the baseline for this line from the top of the paragraph. - /// - /// The bottom edge of the paragraph up to and including this line may be obtained - /// through `baseline + descent`. - /// {@endtemplate} double get baseline; - - /// {@template dart.ui.LineMetrics.lineNumber} - /// The number of this line in the overall paragraph, with the first line being - /// index zero. - /// - /// For example, the first line is line 0, second line is line 1. - /// {@endtemplate} int get lineNumber; } -/// A paragraph of text. -/// -/// A paragraph retains the size and position of each glyph in the text and can -/// be efficiently resized and painted. -/// -/// To create a [Paragraph] object, use a [ParagraphBuilder]. -/// -/// Paragraphs can be displayed on a [Canvas] using the [Canvas.drawParagraph] -/// method. abstract class Paragraph { - /// The amount of horizontal space this paragraph occupies. - /// - /// Valid only after [layout] has been called. double get width; - - /// The amount of vertical space this paragraph occupies. - /// - /// Valid only after [layout] has been called. double get height; - - /// The distance from the left edge of the leftmost glyph to the right edge of - /// the rightmost glyph in the paragraph. - /// - /// Valid only after [layout] has been called. double get longestLine; - - /// {@template dart.ui.paragraph.minIntrinsicWidth} - /// The minimum width that this paragraph could be without failing to paint - /// its contents within itself. - /// {@endtemplate} - /// - /// Valid only after [layout] has been called. double get minIntrinsicWidth; - - /// {@template dart.ui.paragraph.maxIntrinsicWidth} - /// Returns the smallest width beyond which increasing the width never - /// decreases the height. - /// {@endtemplate} - /// - /// Valid only after [layout] has been called. double get maxIntrinsicWidth; - - /// {@template dart.ui.paragraph.alphabeticBaseline} - /// The distance from the top of the paragraph to the alphabetic - /// baseline of the first line, in logical pixels. - /// {@endtemplate} - /// - /// Valid only after [layout] has been called. double get alphabeticBaseline; - - /// {@template dart.ui.paragraph.ideographicBaseline} - /// The distance from the top of the paragraph to the ideographic - /// baseline of the first line, in logical pixels. - /// {@endtemplate} - /// - /// Valid only after [layout] has been called. double get ideographicBaseline; - - /// True if there is more vertical content, but the text was truncated, either - /// because we reached `maxLines` lines of text or because the `maxLines` was - /// null, `ellipsis` was not null, and one of the lines exceeded the width - /// constraint. - /// - /// See the discussion of the `maxLines` and `ellipsis` arguments at [new - /// ParagraphStyle]. bool get didExceedMaxLines; - - /// Computes the size and position of each glyph in the paragraph. - /// - /// The [ParagraphConstraints] control how wide the text is allowed to be. void layout(ParagraphConstraints constraints); - - /// Returns a list of text boxes that enclose the given text range. - /// - /// The [boxHeightStyle] and [boxWidthStyle] parameters allow customization - /// of how the boxes are bound vertically and horizontally. Both style - /// parameters default to the tight option, which will provide close-fitting - /// boxes and will not account for any line spacing. - /// - /// The [boxHeightStyle] and [boxWidthStyle] parameters must not be null. - /// - /// See [BoxHeightStyle] and [BoxWidthStyle] for full descriptions of each option. List getBoxesForRange(int start, int end, {BoxHeightStyle boxHeightStyle = BoxHeightStyle.tight, BoxWidthStyle boxWidthStyle = BoxWidthStyle.tight}); - - /// Returns the text position closest to the given offset. - /// - /// It does so by performing a binary search to find where the tap occurred - /// within the text. TextPosition getPositionForOffset(Offset offset); - - /// Returns the [TextRange] of the word at the given [TextPosition]. - /// - /// Characters not part of a word, such as spaces, symbols, and punctuation, - /// have word breaks on both sides. In such cases, this method will return - /// [offset, offset+1]. Word boundaries are defined more precisely in Unicode - /// Standard Annex #29 http://www.unicode.org/reports/tr29/#Word_Boundaries TextRange getWordBoundary(TextPosition position); - - /// Returns the [TextRange] of the line at the given [TextPosition]. - /// - /// The newline (if any) is returned as part of the range. - /// - /// Not valid until after layout. - /// - /// This can potentially be expensive, since it needs to compute the line - /// metrics, so use it sparingly. TextRange getLineBoundary(TextPosition position); - - /// Returns a list of text boxes that enclose all placeholders in the paragraph. - /// - /// The order of the boxes are in the same order as passed in through [addPlaceholder]. - /// - /// Coordinates of the [TextBox] are relative to the upper-left corner of the paragraph, - /// where positive y values indicate down. List getBoxesForPlaceholders(); - - /// Returns the full list of [LineMetrics] that describe in detail the various - /// metrics of each laid out line. - /// - /// Not valid until after layout. - /// - /// This can potentially return a large amount of data, so it is not recommended - /// to repeatedly call this. Instead, cache the results. List computeLineMetrics(); } -/// Builds a [Paragraph] containing text with the given styling information. -/// -/// To set the paragraph's alignment, truncation, and ellipsising behavior, pass -/// an appropriately-configured [ParagraphStyle] object to the [new -/// ParagraphBuilder] constructor. -/// -/// Then, call combinations of [pushStyle], [addText], and [pop] to add styled -/// text to the object. -/// -/// Finally, call [build] to obtain the constructed [Paragraph] object. After -/// this point, the builder is no longer usable. -/// -/// After constructing a [Paragraph], call [Paragraph.layout] on it and then -/// paint it with [Canvas.drawParagraph]. abstract class ParagraphBuilder { - /// Creates a [ParagraphBuilder] object, which is used to create a - /// [Paragraph]. factory ParagraphBuilder(ParagraphStyle style) { if (engine.experimentalUseSkia) { return engine.CkParagraphBuilder(style); @@ -1490,81 +592,12 @@ abstract class ParagraphBuilder { return engine.EngineParagraphBuilder(style as engine.EngineParagraphStyle); } } - - /// Applies the given style to the added text until [pop] is called. - /// - /// See [pop] for details. void pushStyle(TextStyle style); - - /// Ends the effect of the most recent call to [pushStyle]. - /// - /// Internally, the paragraph builder maintains a stack of text styles. Text - /// added to the paragraph is affected by all the styles in the stack. Calling - /// [pop] removes the topmost style in the stack, leaving the remaining styles - /// in effect. void pop(); - - /// Adds the given text to the paragraph. - /// - /// The text will be styled according to the current stack of text styles. void addText(String text); - - /// Applies the given paragraph style and returns a [Paragraph] containing the - /// added text and associated styling. - /// - /// After calling this function, the paragraph builder object is invalid and - /// cannot be used further. Paragraph build(); - - /// The number of placeholders currently in the paragraph. int get placeholderCount; - - /// The scales of the placeholders in the paragraph. List get placeholderScales; - - /// Adds an inline placeholder space to the paragraph. - /// - /// The paragraph will contain a rectangular space with no text of the dimensions - /// specified. - /// - /// The `width` and `height` parameters specify the size of the placeholder rectangle. - /// - /// The `alignment` parameter specifies how the placeholder rectangle will be vertically - /// aligned with the surrounding text. When [PlaceholderAlignment.baseline], - /// [PlaceholderAlignment.aboveBaseline], and [PlaceholderAlignment.belowBaseline] - /// alignment modes are used, the baseline needs to be set with the `baseline`. - /// When using [PlaceholderAlignment.baseline], `baselineOffset` indicates the distance - /// of the baseline down from the top of of the rectangle. The default `baselineOffset` - /// is the `height`. - /// - /// Examples: - /// - /// * For a 30x50 placeholder with the bottom edge aligned with the bottom of the text, use: - /// `addPlaceholder(30, 50, PlaceholderAlignment.bottom);` - /// * For a 30x50 placeholder that is vertically centered around the text, use: - /// `addPlaceholder(30, 50, PlaceholderAlignment.middle);`. - /// * For a 30x50 placeholder that sits completely on top of the alphabetic baseline, use: - /// `addPlaceholder(30, 50, PlaceholderAlignment.aboveBaseline, baseline: TextBaseline.alphabetic)`. - /// * For a 30x50 placeholder with 40 pixels above and 10 pixels below the alphabetic baseline, use: - /// `addPlaceholder(30, 50, PlaceholderAlignment.baseline, baseline: TextBaseline.alphabetic, baselineOffset: 40)`. - /// - /// Lines are permitted to break around each placeholder. - /// - /// Decorations will be drawn based on the font defined in the most recently - /// pushed [TextStyle]. The decorations are drawn as if unicode text were present - /// in the placeholder space, and will draw the same regardless of the height and - /// alignment of the placeholder. To hide or manually adjust decorations to fit, - /// a text style with the desired decoration behavior should be pushed before - /// adding a placeholder. - /// - /// Any decorations drawn through a placeholder will exist on the same canvas/layer - /// as the text. This means any content drawn on top of the space reserved by - /// the placeholder will be drawn over the decoration, possibly obscuring the - /// decoration. - /// - /// Placeholders are represented by a unicode 0xFFFC "object replacement character" - /// in the text buffer. For each placeholder, one object replacement character is - /// added on to the text buffer. void addPlaceholder( double width, double height, @@ -1575,15 +608,10 @@ abstract class ParagraphBuilder { }); } -/// Loads a font from a buffer and makes it available for rendering text. -/// -/// * `list`: A list of bytes containing the font file. -/// * `fontFamily`: The family name used to identify the font in text styles. -/// If this is not provided, then the family name will be extracted from the font file. Future loadFontFromList(Uint8List list, {String? fontFamily}) { if (engine.experimentalUseSkia) { return engine.skiaFontCollection.loadFontFromList(list, fontFamily: fontFamily).then( - (_) => engine.sendFontChangeMessage() + (_) => engine.sendFontChangeMessage() ); } else { return _fontCollection!.loadFontFromList(list, fontFamily: fontFamily!).then( diff --git a/engine/src/flutter/lib/web_ui/lib/src/ui/tile_mode.dart b/engine/src/flutter/lib/web_ui/lib/src/ui/tile_mode.dart index 9ce9ddf3c2..567b9a5515 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/ui/tile_mode.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/ui/tile_mode.dart @@ -5,53 +5,9 @@ // @dart = 2.10 part of ui; -/// Defines what happens at the edge of the gradient. -/// -/// A gradient is defined along a finite inner area. In the case of a linear -/// gradient, it's between the parallel lines that are orthogonal to the line -/// drawn between two points. In the case of radial gradients, it's the disc -/// that covers the circle centered on a particular point up to a given radius. -/// -/// This enum is used to define how the gradient should paint the regions -/// outside that defined inner area. -/// -/// See also: -/// -/// * [painting.Gradient], the superclass for [LinearGradient] and -/// [RadialGradient], as used by [BoxDecoration] et al, which works in -/// relative coordinates and can create a [Shader] representing the gradient -/// for a particular [Rect] on demand. -/// * [dart:ui.Gradient], the low-level class used when dealing with the -/// [Paint.shader] property directly, with its [new Gradient.linear] and [new -/// Gradient.radial] constructors. // These enum values must be kept in sync with SkShader::TileMode. enum TileMode { - /// Edge is clamped to the final color. - /// - /// The gradient will paint the all the regions outside the inner area with - /// the color of the point closest to that region. - /// - /// ![](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/tile_mode_clamp_radial.png) clamp, - - /// Edge is repeated from first color to last. - /// - /// This is as if the stop points from 0.0 to 1.0 were then repeated from 1.0 - /// to 2.0, 2.0 to 3.0, and so forth (and for linear gradients, similarly from - /// -1.0 to 0.0, -2.0 to -1.0, etc). - /// - /// ![](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/tile_mode_repeated_linear.png) - /// ![](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/tile_mode_repeated_radial.png) repeated, - - /// Edge is mirrored from last color to first. - /// - /// This is as if the stop points from 0.0 to 1.0 were then repeated backwards - /// from 2.0 to 1.0, then forwards from 2.0 to 3.0, then backwards again from - /// 4.0 to 3.0, and so forth (and for linear gradients, similarly from in the - /// negative direction). - /// - /// ![](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/tile_mode_mirror_linear.png) - /// ![](https://flutter.github.io/assets-for-api-docs/assets/dart-ui/tile_mode_mirror_radial.png) mirror, } diff --git a/engine/src/flutter/lib/web_ui/lib/src/ui/window.dart b/engine/src/flutter/lib/web_ui/lib/src/ui/window.dart index deaad0df46..fa58ff01e5 100644 --- a/engine/src/flutter/lib/web_ui/lib/src/ui/window.dart +++ b/engine/src/flutter/lib/web_ui/lib/src/ui/window.dart @@ -6,127 +6,35 @@ // @dart = 2.10 part of ui; -/// Signature of callbacks that have no arguments and return no data. typedef VoidCallback = void Function(); - -/// Signature for frame-related callbacks from the scheduler. -/// -/// The `timeStamp` is the number of milliseconds since the beginning of the -/// scheduler's epoch. Use timeStamp to determine how far to advance animation -/// timelines so that all the animations in the system are synchronized to a -/// common time base. typedef FrameCallback = void Function(Duration duration); - -/// Signature for [Window.onReportTimings]. typedef TimingsCallback = void Function(List timings); - -/// Signature for [Window.onPointerDataPacket]. typedef PointerDataPacketCallback = void Function(PointerDataPacket packet); - -/// Signature for [Window.onSemanticsAction]. -typedef SemanticsActionCallback = void Function( - int id, SemanticsAction action, ByteData? args); - -/// Signature for responses to platform messages. -/// -/// Used as a parameter to [Window.sendPlatformMessage] and -/// [Window.onPlatformMessage]. +typedef SemanticsActionCallback = void Function(int id, SemanticsAction action, ByteData? args); typedef PlatformMessageResponseCallback = void Function(ByteData? data); - -/// Signature for [Window.onPlatformMessage]. typedef PlatformMessageCallback = void Function( String name, ByteData? data, PlatformMessageResponseCallback? callback); -/// States that an application can be in. -/// -/// The values below describe notifications from the operating system. -/// Applications should not expect to always receive all possible -/// notifications. For example, if the users pulls out the battery from the -/// device, no notification will be sent before the application is suddenly -/// terminated, along with the rest of the operating system. -/// -/// See also: -/// -/// * [WidgetsBindingObserver], for a mechanism to observe the lifecycle state -/// from the widgets layer. enum AppLifecycleState { - /// The application is visible and responding to user input. resumed, - - /// The application is in an inactive state and is not receiving user input. - /// - /// On iOS, this state corresponds to an app or the Flutter host view running - /// in the foreground inactive state. Apps transition to this state when in - /// a phone call, responding to a TouchID request, when entering the app - /// switcher or the control center, or when the UIViewController hosting the - /// Flutter app is transitioning. - /// - /// On Android, this corresponds to an app or the Flutter host view running - /// in the foreground inactive state. Apps transition to this state when - /// another activity is focused, such as a split-screen app, a phone call, - /// a picture-in-picture app, a system dialog, or another window. - /// - /// Apps in this state should assume that they may be [paused] at any time. inactive, - - /// The application is not currently visible to the user, not responding to - /// user input, and running in the background. - /// - /// When the application is in this state, the engine will not call the - /// [Window.onBeginFrame] and [Window.onDrawFrame] callbacks. paused, - - /// The application is detached from view. - /// - /// When the application is in this state, the engine is running without - /// a platform UI. detached, } -/// A representation of distances for each of the four edges of a rectangle, -/// used to encode the view insets and padding that applications should place -/// around their user interface, as exposed by [Window.viewInsets] and -/// [Window.padding]. View insets and padding are preferably read via -/// [MediaQuery.of]. -/// -/// For the engine implementation of this class see the [engine.WindowPadding]. -/// -/// For a generic class that represents distances around a rectangle, see the -/// [EdgeInsets] class. -/// -/// See also: -/// -/// * [WidgetsBindingObserver], for a widgets layer mechanism to receive -/// notifications when the padding changes. -/// * [MediaQuery.of], for the preferred mechanism for accessing these values. -/// * [Scaffold], which automatically applies the padding in material design -/// applications. abstract class WindowPadding { - const factory WindowPadding._( - {required double left, - required double top, - required double right, - required double bottom}) = engine.WindowPadding; + const factory WindowPadding._({ + required double left, + required double top, + required double right, + required double bottom, + }) = engine.WindowPadding; - /// The distance from the left edge to the first unpadded pixel, in physical - /// pixels. double get left; - - /// The distance from the top edge to the first unpadded pixel, in physical - /// pixels. double get top; - - /// The distance from the right edge to the first unpadded pixel, in physical - /// pixels. double get right; - - /// The distance from the bottom edge to the first unpadded pixel, in physical - /// pixels. double get bottom; - - /// A window padding that has zeros for each edge. - static const WindowPadding zero = - WindowPadding._(left: 0.0, top: 0.0, right: 0.0, bottom: 0.0); + static const WindowPadding zero = WindowPadding._(left: 0.0, top: 0.0, right: 0.0, bottom: 0.0); @override String toString() { @@ -134,79 +42,13 @@ abstract class WindowPadding { } } -/// An identifier used to select a user's language and formatting preferences. -/// -/// This represents a [Unicode Language -/// Identifier](https://www.unicode.org/reports/tr35/#Unicode_language_identifier) -/// (i.e. without Locale extensions), except variants are not supported. -/// -/// Locales are canonicalized according to the "preferred value" entries in the -/// [IANA Language Subtag -/// Registry](https://www.iana.org/assignments/language-subtag-registry/language-subtag-registry). -/// For example, `const Locale('he')` and `const Locale('iw')` are equal and -/// both have the [languageCode] `he`, because `iw` is a deprecated language -/// subtag that was replaced by the subtag `he`. -/// -/// See also: -/// -/// * [Window.locale], which specifies the system's currently selected -/// [Locale]. class Locale { - /// Creates a new Locale object. The first argument is the - /// primary language subtag, the second is the region (also - /// referred to as 'country') subtag. - /// - /// For example: - /// - /// ```dart - /// const Locale swissFrench = const Locale('fr', 'CH'); - /// const Locale canadianFrench = const Locale('fr', 'CA'); - /// ``` - /// - /// The primary language subtag must not be null. The region subtag is - /// optional. When there is no region/country subtag, the parameter should - /// be omitted or passed `null` instead of an empty-string. - /// - /// The subtag values are _case sensitive_ and must be one of the valid - /// subtags according to CLDR supplemental data: - /// [language](http://unicode.org/cldr/latest/common/validity/language.xml), - /// [region](http://unicode.org/cldr/latest/common/validity/region.xml). The - /// primary language subtag must be at least two and at most eight lowercase - /// letters, but not four letters. The region region subtag must be two - /// uppercase letters or three digits. See the [Unicode Language - /// Identifier](https://www.unicode.org/reports/tr35/#Unicode_language_identifier) - /// specification. - /// - /// Validity is not checked by default, but some methods may throw away - /// invalid data. - /// - /// See also: - /// - /// * [new Locale.fromSubtags], which also allows a [scriptCode] to be - /// specified. const Locale( this._languageCode, [ this._countryCode, ]) : assert(_languageCode != null), // ignore: unnecessary_null_comparison assert(_languageCode != ''), scriptCode = null; - - /// Creates a new Locale object. - /// - /// The keyword arguments specify the subtags of the Locale. - /// - /// The subtag values are _case sensitive_ and must be valid subtags according - /// to CLDR supplemental data: - /// [language](http://unicode.org/cldr/latest/common/validity/language.xml), - /// [script](http://unicode.org/cldr/latest/common/validity/script.xml) and - /// [region](http://unicode.org/cldr/latest/common/validity/region.xml) for - /// each of languageCode, scriptCode and countryCode respectively. - /// - /// The [countryCode] subtag is optional. When there is no country subtag, - /// the parameter should be omitted or passed `null` instead of an empty-string. - /// - /// Validity is not checked by default, but some methods may throw away - /// invalid data. const Locale.fromSubtags({ String languageCode = 'und', this.scriptCode, @@ -217,30 +59,6 @@ class Locale { assert(scriptCode != ''), assert(countryCode != ''), _countryCode = countryCode; - - /// The primary language subtag for the locale. - /// - /// This must not be null. It may be 'und', representing 'undefined'. - /// - /// This is expected to be string registered in the [IANA Language Subtag - /// Registry](https://www.iana.org/assignments/language-subtag-registry/language-subtag-registry) - /// with the type "language". The string specified must match the case of the - /// string in the registry. - /// - /// Language subtags that are deprecated in the registry and have a preferred - /// code are changed to their preferred code. For example, `const - /// Locale('he')` and `const Locale('iw')` are equal, and both have the - /// [languageCode] `he`, because `iw` is a deprecated language subtag that was - /// replaced by the subtag `he`. - /// - /// This must be a valid Unicode Language subtag as listed in [Unicode CLDR - /// supplemental - /// data](http://unicode.org/cldr/latest/common/validity/language.xml). - /// - /// See also: - /// - /// * [new Locale.fromSubtags], which describes the conventions for creating - /// [Locale] objects. String get languageCode => _deprecatedLanguageSubtagMap[_languageCode] ?? _languageCode; final String _languageCode; @@ -326,40 +144,7 @@ class Locale { 'yos': 'zom', // Yos; deprecated 2013-09-10 'yuu': 'yug', // Yugh; deprecated 2014-02-28 }; - - /// The script subtag for the locale. - /// - /// This may be null, indicating that there is no specified script subtag. - /// - /// This must be a valid Unicode Language Identifier script subtag as listed - /// in [Unicode CLDR supplemental - /// data](http://unicode.org/cldr/latest/common/validity/script.xml). - /// - /// See also: - /// - /// * [new Locale.fromSubtags], which describes the conventions for creating - /// [Locale] objects. final String? scriptCode; - - /// The region subtag for the locale. - /// - /// This may be null, indicating that there is no specified region subtag. - /// - /// This is expected to be string registered in the [IANA Language Subtag - /// Registry](https://www.iana.org/assignments/language-subtag-registry/language-subtag-registry) - /// with the type "region". The string specified must match the case of the - /// string in the registry. - /// - /// Region subtags that are deprecated in the registry and have a preferred - /// code are changed to their preferred code. For example, `const Locale('de', - /// 'DE')` and `const Locale('de', 'DD')` are equal, and both have the - /// [countryCode] `DE`, because `DD` is a deprecated language subtag that was - /// replaced by the subtag `DE`. - /// - /// See also: - /// - /// * [new Locale.fromSubtags], which describes the conventions for creating - /// [Locale] objects. String? get countryCode => _deprecatedRegionSubtagMap[_countryCode] ?? _countryCode; final String? _countryCode; @@ -406,410 +191,65 @@ class Locale { } } -/// The most basic interface to the host operating system's user interface. -/// -/// There is a single Window instance in the system, which you can -/// obtain from the [window] property. abstract class Window { - /// The number of device pixels for each logical pixel. This number might not - /// be a power of two. Indeed, it might not even be an integer. For example, - /// the Nexus 6 has a device pixel ratio of 3.5. - /// - /// Device pixels are also referred to as physical pixels. Logical pixels are - /// also referred to as device-independent or resolution-independent pixels. - /// - /// By definition, there are roughly 38 logical pixels per centimeter, or - /// about 96 logical pixels per inch, of the physical display. The value - /// returned by [devicePixelRatio] is ultimately obtained either from the - /// hardware itself, the device drivers, or a hard-coded value stored in the - /// operating system or firmware, and may be inaccurate, sometimes by a - /// significant margin. - /// - /// The Flutter framework operates in logical pixels, so it is rarely - /// necessary to directly deal with this property. - /// - /// When this changes, [onMetricsChanged] is called. - /// - /// See also: - /// - /// * [WidgetsBindingObserver], for a mechanism at the widgets layer to - /// observe when this value changes. double get devicePixelRatio; - - /// The dimensions of the rectangle into which the application will be drawn, - /// in physical pixels. - /// - /// When this changes, [onMetricsChanged] is called. - /// - /// At startup, the size of the application window may not be known before - /// Dart code runs. If this value is observed early in the application - /// lifecycle, it may report [Size.zero]. - /// - /// This value does not take into account any on-screen keyboards or other - /// system UI. The [padding] and [viewInsets] properties provide a view into - /// how much of each side of the application may be obscured by system UI. - /// - /// See also: - /// - /// * [WidgetsBindingObserver], for a mechanism at the widgets layer to - /// observe when this value changes. Size get physicalSize; - - /// The number of physical pixels on each side of the display rectangle into - /// which the application can render, but over which the operating system - /// will likely place system UI, such as the keyboard, that fully obscures - /// any content. - /// - /// When this changes, [onMetricsChanged] is called. - /// - /// See also: - /// - /// * [WidgetsBindingObserver], for a mechanism at the widgets layer to - /// observe when this value changes. - /// * [MediaQuery.of], a simpler mechanism for the same. - /// * [Scaffold], which automatically applies the view insets in material - /// design applications. WindowPadding get viewInsets => WindowPadding.zero; WindowPadding get viewPadding => WindowPadding.zero; WindowPadding get systemGestureInsets => WindowPadding.zero; - - /// The number of physical pixels on each side of the display rectangle into - /// which the application can render, but which may be partially obscured by - /// system UI (such as the system notification area), or or physical - /// intrusions in the display (e.g. overscan regions on television screens or - /// phone sensor housings). - /// - /// When this changes, [onMetricsChanged] is called. - /// - /// See also: - /// - /// * [WidgetsBindingObserver], for a mechanism at the widgets layer to - /// observe when this value changes. - /// * [MediaQuery.of], a simpler mechanism for the same. - /// * [Scaffold], which automatically applies the padding in material design - /// applications. WindowPadding get padding => WindowPadding.zero; - - /// The system-reported text scale. - /// - /// This establishes the text scaling factor to use when rendering text, - /// according to the user's platform preferences. - /// - /// The [onTextScaleFactorChanged] callback is called whenever this value - /// changes. - /// - /// See also: - /// - /// * [WidgetsBindingObserver], for a mechanism at the widgets layer to - /// observe when this value changes. double get textScaleFactor => _textScaleFactor; double _textScaleFactor = 1.0; - - /// The setting indicating whether time should always be shown in the 24-hour - /// format. - /// - /// This option is used by [showTimePicker]. bool get alwaysUse24HourFormat => _alwaysUse24HourFormat; bool _alwaysUse24HourFormat = false; - - /// A callback that is invoked whenever [textScaleFactor] changes value. - /// - /// The framework invokes this callback in the same zone in which the - /// callback was set. - /// - /// See also: - /// - /// * [WidgetsBindingObserver], for a mechanism at the widgets layer to - /// observe when this callback is invoked. VoidCallback? get onTextScaleFactorChanged; set onTextScaleFactorChanged(VoidCallback? callback); - - /// The setting indicating the current brightness mode of the host platform. Brightness get platformBrightness; - - /// A callback that is invoked whenever [platformBrightness] changes value. - /// - /// The framework invokes this callback in the same zone in which the - /// callback was set. - /// - /// See also: - /// - /// * [WidgetsBindingObserver], for a mechanism at the widgets layer to - /// observe when this callback is invoked. VoidCallback? get onPlatformBrightnessChanged; set onPlatformBrightnessChanged(VoidCallback? callback); - - /// A callback that is invoked whenever the [devicePixelRatio], - /// [physicalSize], [padding], or [viewInsets] values change, for example - /// when the device is rotated or when the application is resized (e.g. when - /// showing applications side-by-side on Android). - /// - /// The engine invokes this callback in the same zone in which the callback - /// was set. - /// - /// The framework registers with this callback and updates the layout - /// appropriately. - /// - /// See also: - /// - /// * [WidgetsBindingObserver], for a mechanism at the widgets layer to - /// register for notifications when this is called. - /// * [MediaQuery.of], a simpler mechanism for the same. VoidCallback? get onMetricsChanged; set onMetricsChanged(VoidCallback? callback); - - /// The system-reported default locale of the device. - /// - /// This establishes the language and formatting conventions that application - /// should, if possible, use to render their user interface. - /// - /// This is the first locale selected by the user and is the user's - /// primary locale (the locale the device UI is displayed in) - /// - /// This is equivalent to `locales.first` and will provide an empty non-null locale - /// if the [locales] list has not been set or is empty. Locale? get locale; - - /// The full system-reported supported locales of the device. - /// - /// This establishes the language and formatting conventions that application - /// should, if possible, use to render their user interface. - /// - /// The list is ordered in order of priority, with lower-indexed locales being - /// preferred over higher-indexed ones. The first element is the primary [locale]. - /// - /// The [onLocaleChanged] callback is called whenever this value changes. - /// - /// See also: - /// - /// * [WidgetsBindingObserver], for a mechanism at the widgets layer to - /// observe when this value changes. List? get locales; - - /// Performs the platform-native locale resolution. - /// - /// Each platform may return different results. - /// - /// If the platform fails to resolve a locale, then this will return null. - /// - /// This method returns synchronously and is a direct call to - /// platform specific APIs without invoking method channels. Locale? computePlatformResolvedLocale(List supportedLocales) { // TODO(garyq): Implement on web. return null; } - /// A callback that is invoked whenever [locale] changes value. - /// - /// The framework invokes this callback in the same zone in which the - /// callback was set. - /// - /// See also: - /// - /// * [WidgetsBindingObserver], for a mechanism at the widgets layer to - /// observe when this callback is invoked. VoidCallback? get onLocaleChanged; set onLocaleChanged(VoidCallback? callback); - - /// Requests that, at the next appropriate opportunity, the [onBeginFrame] - /// and [onDrawFrame] callbacks be invoked. - /// - /// See also: - /// - /// * [SchedulerBinding], the Flutter framework class which manages the - /// scheduling of frames. void scheduleFrame(); - - /// A callback that is invoked to notify the application that it is an - /// appropriate time to provide a scene using the [SceneBuilder] API and the - /// [render] method. When possible, this is driven by the hardware VSync - /// signal. This is only called if [scheduleFrame] has been called since the - /// last time this callback was invoked. - /// - /// The [onDrawFrame] callback is invoked immediately after [onBeginFrame], - /// after draining any microtasks (e.g. completions of any [Future]s) queued - /// by the [onBeginFrame] handler. - /// - /// The framework invokes this callback in the same zone in which the - /// callback was set. - /// - /// See also: - /// - /// * [SchedulerBinding], the Flutter framework class which manages the - /// scheduling of frames. - /// * [RendererBinding], the Flutter framework class which manages layout and - /// painting. FrameCallback? get onBeginFrame; set onBeginFrame(FrameCallback? callback); - - /// A callback that is invoked to report the [FrameTiming] of recently - /// rasterized frames. - /// - /// This can be used to see if the application has missed frames (through - /// [FrameTiming.buildDuration] and [FrameTiming.rasterDuration]), or high - /// latencies (through [FrameTiming.totalSpan]). - /// - /// Unlike [Timeline], the timing information here is available in the release - /// mode (additional to the profile and the debug mode). Hence this can be - /// used to monitor the application's performance in the wild. - /// - /// The callback may not be immediately triggered after each frame. Instead, - /// it tries to batch frames together and send all their timings at once to - /// decrease the overhead (as this is available in the release mode). The - /// timing of any frame will be sent within about 1 second even if there are - /// no later frames to batch. TimingsCallback? get onReportTimings; set onReportTimings(TimingsCallback? callback); - - /// A callback that is invoked for each frame after [onBeginFrame] has - /// completed and after the microtask queue has been drained. This can be - /// used to implement a second phase of frame rendering that happens - /// after any deferred work queued by the [onBeginFrame] phase. - /// - /// The framework invokes this callback in the same zone in which the - /// callback was set. - /// - /// See also: - /// - /// * [SchedulerBinding], the Flutter framework class which manages the - /// scheduling of frames. - /// * [RendererBinding], the Flutter framework class which manages layout and - /// painting. VoidCallback? get onDrawFrame; set onDrawFrame(VoidCallback? callback); - - /// A callback that is invoked when pointer data is available. - /// - /// The framework invokes this callback in the same zone in which the - /// callback was set. - /// - /// See also: - /// - /// * [GestureBinding], the Flutter framework class which manages pointer - /// events. PointerDataPacketCallback? get onPointerDataPacket; set onPointerDataPacket(PointerDataPacketCallback? callback); - - /// The route or path that the embedder requested when the application was - /// launched. - /// - /// This will be the string "`/`" if no particular route was requested. - /// - /// See also: - /// - /// * [Navigator], a widget that handles routing. - /// * [SystemChannels.navigation], which handles subsequent navigation - /// requests from the embedder. String get defaultRouteName; - - /// Whether the user has requested that [updateSemantics] be called when - /// the semantic contents of window changes. - /// - /// The [onSemanticsEnabledChanged] callback is called whenever this value - /// changes. - /// - /// This defaults to `true` on the Web because we may never receive a signal - /// that an assistive technology is turned on. - bool get semanticsEnabled => - engine.EngineSemanticsOwner.instance.semanticsEnabled; - - /// A callback that is invoked when the value of [semanticsEnabled] changes. - /// - /// The framework invokes this callback in the same zone in which the - /// callback was set. + bool get semanticsEnabled => engine.EngineSemanticsOwner.instance.semanticsEnabled; VoidCallback? get onSemanticsEnabledChanged; set onSemanticsEnabledChanged(VoidCallback? callback); - - /// A callback that is invoked whenever the user requests an action to be - /// performed. - /// - /// This callback is used when the user expresses the action they wish to - /// perform based on the semantics supplied by [updateSemantics]. - /// - /// The framework invokes this callback in the same zone in which the - /// callback was set. SemanticsActionCallback? get onSemanticsAction; set onSemanticsAction(SemanticsActionCallback? callback); - - /// A callback that is invoked when the value of [accessibilityFlags] changes. - /// - /// The framework invokes this callback in the same zone in which the - /// callback was set. VoidCallback? get onAccessibilityFeaturesChanged; set onAccessibilityFeaturesChanged(VoidCallback? callback); - - /// Called whenever this window receives a message from a platform-specific - /// plugin. - /// - /// The `name` parameter determines which plugin sent the message. The `data` - /// parameter is the payload and is typically UTF-8 encoded JSON but can be - /// arbitrary data. - /// - /// Message handlers must call the function given in the `callback` parameter. - /// If the handler does not need to respond, the handler should pass null to - /// the callback. - /// - /// The framework invokes this callback in the same zone in which the - /// callback was set. PlatformMessageCallback? get onPlatformMessage; set onPlatformMessage(PlatformMessageCallback? callback); - - /// Change the retained semantics data about this window. - /// - /// If [semanticsEnabled] is true, the user has requested that this funciton - /// be called whenever the semantic content of this window changes. - /// - /// In either case, this function disposes the given update, which means the - /// semantics update cannot be used further. void updateSemantics(SemanticsUpdate update) { engine.EngineSemanticsOwner.instance.updateSemantics(update); } - /// Sends a message to a platform-specific plugin. - /// - /// The `name` parameter determines which plugin receives the message. The - /// `data` parameter contains the message payload and is typically UTF-8 - /// encoded JSON but can be arbitrary data. If the plugin replies to the - /// message, `callback` will be called with the response. - /// - /// The framework invokes [callback] in the same zone in which this method - /// was called. void sendPlatformMessage( String name, ByteData? data, PlatformMessageResponseCallback? callback, ); - - /// Additional accessibility features that may be enabled by the platform. AccessibilityFeatures get accessibilityFeatures => _accessibilityFeatures; AccessibilityFeatures _accessibilityFeatures = AccessibilityFeatures._(0); - - /// Updates the application's rendering on the GPU with the newly provided - /// [Scene]. This function must be called within the scope of the - /// [onBeginFrame] or [onDrawFrame] callbacks being invoked. If this function - /// is called a second time during a single [onBeginFrame]/[onDrawFrame] - /// callback sequence or called outside the scope of those callbacks, the call - /// will be ignored. - /// - /// To record graphical operations, first create a [PictureRecorder], then - /// construct a [Canvas], passing that [PictureRecorder] to its constructor. - /// After issuing all the graphical operations, call the - /// [PictureRecorder.endRecording] function on the [PictureRecorder] to obtain - /// the final [Picture] that represents the issued graphical operations. - /// - /// Next, create a [SceneBuilder], and add the [Picture] to it using - /// [SceneBuilder.addPicture]. With the [SceneBuilder.build] method you can - /// then obtain a [Scene] object, which you can display to the user via this - /// [render] function. - /// - /// See also: - /// - /// * [SchedulerBinding], the Flutter framework class which manages the - /// scheduling of frames. - /// * [RendererBinding], the Flutter framework class which manages layout and - /// painting. void render(Scene scene); String get initialLifecycleState => 'AppLifecycleState.resumed'; @@ -819,11 +259,6 @@ abstract class Window { ByteData? getPersistentIsolateData() => null; } -/// Additional accessibility features that may be enabled by the platform. -/// -/// It is not possible to enable these settings from Flutter, instead they are -/// used by the platform to indicate that additional accessibility features are -/// enabled. class AccessibilityFeatures { const AccessibilityFeatures._(this._index); @@ -836,33 +271,11 @@ class AccessibilityFeatures { // A bitfield which represents each enabled feature. final int _index; - - /// Whether there is a running accessibility service which is changing the - /// interaction model of the device. - /// - /// For example, TalkBack on Android and VoiceOver on iOS enable this flag. bool get accessibleNavigation => _kAccessibleNavigation & _index != 0; - - /// The platform is inverting the colors of the application. bool get invertColors => _kInvertColorsIndex & _index != 0; - - /// The platform is requesting that animations be disabled or simplified. bool get disableAnimations => _kDisableAnimationsIndex & _index != 0; - - /// The platform is requesting that text be rendered at a bold font weight. - /// - /// Only supported on iOS. bool get boldText => _kBoldTextIndex & _index != 0; - - /// The platform is requesting that certain animations be simplified and - /// parallax effects removed. - /// - /// Only supported on iOS. bool get reduceMotion => _kReduceMotionIndex & _index != 0; - - /// The platform is requesting that UI be rendered with darker colors. - /// - /// Only supported on iOS. bool get highContrast => _kHighContrastIndex & _index != 0; @override @@ -902,18 +315,8 @@ class AccessibilityFeatures { int get hashCode => _index.hashCode; } -/// Describes the contrast of a theme or color palette. enum Brightness { - /// The color is dark and will require a light text color to achieve readable - /// contrast. - /// - /// For example, the color might be dark grey, requiring white text. dark, - - /// The color is light and will require a dark text color to achieve readable - /// contrast. - /// - /// For example, the color might be bright white, requiring black text. light, } @@ -968,49 +371,15 @@ class IsolateNameServer { } } -/// Various important time points in the lifetime of a frame. -/// -/// [FrameTiming] records a timestamp of each phase for performance analysis. enum FramePhase { - /// The timestamp of the vsync signal given by the operating system. - /// - /// See also [FrameTiming.vsyncOverhead]. vsyncStart, - - /// When the UI thread starts building a frame. - /// - /// See also [FrameTiming.buildDuration]. buildStart, - - /// When the UI thread finishes building a frame. - /// - /// See also [FrameTiming.buildDuration]. buildFinish, - - /// When the raster thread starts rasterizing a frame. - /// - /// See also [FrameTiming.rasterDuration]. rasterStart, - - /// When the raster thread finishes rasterizing a frame. - /// - /// See also [FrameTiming.rasterDuration]. rasterFinish, } -/// Time-related performance metrics of a frame. -/// -/// See [Window.onReportTimings] for how to get this. -/// -/// The metrics in debug mode (`flutter run` without any flags) may be very -/// different from those in profile and release modes due to the debug overhead. -/// Therefore it's recommended to only monitor and analyze performance metrics -/// in profile and release modes. class FrameTiming { - /// Construct [FrameTiming] with raw timestamps in microseconds. - /// - /// This constructor is used for unit test only. Real [FrameTiming]s should - /// be retrieved from [Window.onReportTimings]. factory FrameTiming({ required int vsyncStart, required int buildStart, @@ -1026,65 +395,17 @@ class FrameTiming { rasterFinish ]); } - - /// Construct [FrameTiming] with raw timestamps in microseconds. - /// - /// List [timestamps] must have the same number of elements as - /// [FramePhase.values]. - /// - /// This constructor is usually only called by the Flutter engine, or a test. - /// To get the [FrameTiming] of your app, see [Window.onReportTimings]. FrameTiming._(List timestamps) - : assert(timestamps.length == FramePhase.values.length), _timestamps = timestamps; + : assert(timestamps.length == FramePhase.values.length), + _timestamps = timestamps; - /// This is a raw timestamp in microseconds from some epoch. The epoch in all - /// [FrameTiming] is the same, but it may not match [DateTime]'s epoch. int timestampInMicroseconds(FramePhase phase) => _timestamps[phase.index]; - Duration _rawDuration(FramePhase phase) => - Duration(microseconds: _timestamps[phase.index]); - - /// The duration to build the frame on the UI thread. - /// - /// The build starts approximately when [Window.onBeginFrame] is called. The - /// [Duration] in the [Window.onBeginFrame] callback is exactly the - /// `Duration(microseconds: timestampInMicroseconds(FramePhase.buildStart))`. - /// - /// The build finishes when [Window.render] is called. - /// - /// {@template dart.ui.FrameTiming.fps_smoothness_milliseconds} - /// To ensure smooth animations of X fps, this should not exceed 1000/X - /// milliseconds. - /// {@endtemplate} - /// {@template dart.ui.FrameTiming.fps_milliseconds} - /// That's about 16ms for 60fps, and 8ms for 120fps. - /// {@endtemplate} - Duration get buildDuration => - _rawDuration(FramePhase.buildFinish) - - _rawDuration(FramePhase.buildStart); - - /// The duration to rasterize the frame on the raster thread. - /// - /// {@macro dart.ui.FrameTiming.fps_smoothness_milliseconds} - /// {@macro dart.ui.FrameTiming.fps_milliseconds} - Duration get rasterDuration => - _rawDuration(FramePhase.rasterFinish) - - _rawDuration(FramePhase.rasterStart); - - /// The duration between receiving the vsync signal and starting building the - /// frame. + Duration _rawDuration(FramePhase phase) => Duration(microseconds: _timestamps[phase.index]); + Duration get buildDuration => _rawDuration(FramePhase.buildFinish) - _rawDuration(FramePhase.buildStart); + Duration get rasterDuration => _rawDuration(FramePhase.rasterFinish) - _rawDuration(FramePhase.rasterStart); Duration get vsyncOverhead => _rawDuration(FramePhase.buildStart) - _rawDuration(FramePhase.vsyncStart); - - /// The timespan between vsync start and raster finish. - /// - /// To achieve the lowest latency on an X fps display, this should not exceed - /// 1000/X milliseconds. - /// {@macro dart.ui.FrameTiming.fps_milliseconds} - /// - /// See also [vsyncOverhead], [buildDuration] and [rasterDuration]. - Duration get totalSpan => - _rawDuration(FramePhase.rasterFinish) - - _rawDuration(FramePhase.vsyncStart); + Duration get totalSpan => _rawDuration(FramePhase.rasterFinish) - _rawDuration(FramePhase.vsyncStart); final List _timestamps; // in microseconds @@ -1096,7 +417,4 @@ class FrameTiming { } } -/// The [Window] singleton. This object exposes the size of the display, the -/// core scheduler API, the input event callback, the graphics drawing API, and -/// other such core services. Window get window => engine.window;