Remove doc comments in copied web interfaces (flutter/engine#20494)

* Remove doc comments in copied web interfaces

* Whitespace changes to improve readability
This commit is contained in:
Greg Spencer
2020-08-18 17:15:16 -07:00
committed by GitHub
parent 8b4e07c198
commit 0764e7cf1a
18 changed files with 284 additions and 6217 deletions

View File

@@ -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 {

View File

@@ -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<Offset> positions, {
@@ -77,34 +31,21 @@ class Vertices {
List<int>? 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<Offset>].
void drawPoints(PointMode pointMode, List<Offset> 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<Offset>] rather than a
/// [List<Float32List>].
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<Sprite> allSprites;
///
/// @override
/// void paint(Canvas canvas, Size size) {
/// Paint paint = Paint();
/// canvas.drawAtlas(spriteAtlas, <RSTransform>[
/// 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,
/// ),
/// ], <Rect>[
/// 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<Sprite> allSprites;
///
/// @override
/// void paint(Canvas canvas, Size size) {
/// Paint paint = Paint();
/// canvas.drawAtlas(spriteAtlas, <RSTransform>[
/// 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,
/// ),
/// ], <Rect>[
/// for (Sprite sprite in allSprites)
/// Rect.fromLTWH(sprite.index * 10.0, 0.0, 10.0, 10.0),
/// ], <Color>[
/// 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<RSTransform> 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<Sprite> 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<Sprite> 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<Image> 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: <https://en.wikipedia.org/wiki/Nonzero-rule>
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: <https://en.wikipedia.org/wiki/Even-odd_rule>
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,
}

View File

@@ -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<T> {
/// The underlying data for the RingBuffer. ListQueues dynamically resize,
/// [_RingBuffer]s do not.
final collection.ListQueue<T> _queue;
_RingBuffer(this._capacity)
: _queue = collection.ListQueue<T>(_capacity);
/// Returns the number of items in the [_RingBuffer].
_RingBuffer(this._capacity) : _queue = collection.ListQueue<T>(_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<T> {
}
}
/// 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<T> {
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<void> 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<String, _RingBuffer<_StoredMessage>?> _messages =
<String, _RingBuffer<_StoredMessage>?>{};
<String, _RingBuffer<_StoredMessage>?>{};
_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<void> 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<channel name>\r<new size>`
/// Description: Allows you to set the size of a channel's buffer.
void handleMessage(ByteData data) {
final List<String> 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();

View File

@@ -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<Image> 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,

File diff suppressed because it is too large Load Diff

View File

@@ -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<Object?>? arguments) {
int result = 0;
if (arguments != null) {

View File

@@ -5,7 +5,6 @@
// @dart = 2.10
part of ui;
/// Initializes the platform.
Future<void> 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<void> 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<void> webOnlySetAssetManager(engine.AssetManager assetManager) async {
_fontCollection!.clear();
}
if (_assetManager != null) {
if (engine.experimentalUseSkia) {
await engine.skiaFontCollection.registerFonts(_assetManager!);
@@ -85,29 +78,16 @@ Future<void> 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!;

View File

@@ -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) {

View File

@@ -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: `<namespace>,<class>,<symbol>\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<int> saveCompilationTrace() {
throw UnimplementedError();
}

File diff suppressed because it is too large Load Diff

View File

@@ -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<Offset> 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});
}

View File

@@ -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<PathMetric> {
@override
Iterator<PathMetric> get iterator;
}
/// Used by [PathMetrics] to track iteration from one segment of a path to the
/// next for measurement.
abstract class PathMetricIterator implements Iterator<PathMetric> {
@override
PathMetric get current;
@@ -35,114 +18,23 @@ abstract class PathMetricIterator implements Iterator<PathMetric> {
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);
}

View File

@@ -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 <PointerData>[] }) : 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 <PointerData>[]})
: assert(data != null); // ignore: unnecessary_null_comparison
final List<PointerData> data;
}

View File

@@ -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<String, int> 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<int, SemanticsAction> values = <int, SemanticsAction>{
_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<int, SemanticsFlag> values = <int, SemanticsFlag>{
_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<engine.SemanticsNodeUpdate> _nodeUpdates =
<engine.SemanticsNodeUpdate>[];
/// 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<engine.SemanticsNodeUpdate> _nodeUpdates = <engine.SemanticsNodeUpdate>[];
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<engine.SemanticsNodeUpdate>? 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();
}

View File

@@ -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<void>? _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<dynamic> ensureTestPlatformInitializedThenRunTest(
dynamic Function() body) {
Future<dynamic> 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<dynamic>((_) => 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<void>? _platformInitializedFuture;
/// Initializes domRenderer with specific devicePixelRatio and physicalSize.
Future<void> webOnlyInitializeTestDomRenderer({double devicePixelRatio = 3.0}) {
// Force-initialize DomRenderer so it doesn't overwrite test pixel ratio.
engine.domRenderer;

File diff suppressed because it is too large Load Diff

View File

@@ -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,
}

View File

@@ -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<FrameTiming> 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<Locale>? 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<Locale> 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<int> 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<int> _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;