borders.dart 36.4 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5
import 'dart:math' as math;
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
import 'dart:ui' as ui show lerpDouble;

import 'package:flutter/foundation.dart';

import 'basic_types.dart';
import 'edge_insets.dart';

/// The style of line to draw for a [BorderSide] in a [Border].
enum BorderStyle {
  /// Skip the border.
  none,

  /// Draw the border as a solid line.
  solid,

  // if you add more, think about how they will lerp
}

/// A side of a border of a box.
///
/// A [Border] consists of four [BorderSide] objects: [Border.top],
/// [Border.left], [Border.right], and [Border.bottom].
///
29 30
/// Setting [BorderSide.width] to 0.0 will result in hairline rendering; see
/// [BorderSide.width] for a more involved explanation.
31
///
32
/// {@tool snippet}
33 34 35 36 37 38
/// This sample shows how [BorderSide] objects can be used in a [Container], via
/// a [BoxDecoration] and a [Border], to decorate some [Text]. In this example,
/// the text has a thick bar above it that is light blue, and a thick bar below
/// it that is a darker shade of blue.
///
/// ```dart
39
/// Container(
40
///   padding: const EdgeInsets.all(8.0),
41 42 43 44
///   decoration: BoxDecoration(
///     border: Border(
///       top: BorderSide(width: 16.0, color: Colors.lightBlue.shade50),
///       bottom: BorderSide(width: 16.0, color: Colors.lightBlue.shade900),
45 46
///     ),
///   ),
47
///   child: const Text('Flutter in the sky', textAlign: TextAlign.center),
48 49
/// )
/// ```
50
/// {@end-tool}
51 52 53 54 55
///
/// See also:
///
///  * [Border], which uses [BorderSide] objects to represent its sides.
///  * [BoxDecoration], which optionally takes a [Border] object.
56
///  * [TableBorder], which is similar to [Border] but has two more sides
57 58 59
///    ([TableBorder.horizontalInside] and [TableBorder.verticalInside]), both
///    of which are also [BorderSide] objects.
@immutable
60
class BorderSide with Diagnosticable {
61 62 63 64
  /// Creates the side of a border.
  ///
  /// By default, the border is 1.0 logical pixels wide and solid black.
  const BorderSide({
65 66 67
    this.color = const Color(0xFF000000),
    this.width = 1.0,
    this.style = BorderStyle.solid,
68
    this.strokeAlign = strokeAlignInside,
69
  }) : assert(width >= 0.0);
70 71 72 73 74 75 76

  /// Creates a [BorderSide] that represents the addition of the two given
  /// [BorderSide]s.
  ///
  /// It is only valid to call this if [canMerge] returns true for the two
  /// sides.
  ///
77 78
  /// If one of the sides is zero-width with [BorderStyle.none], then the other
  /// side is return as-is. If both of the sides are zero-width with
79
  /// [BorderStyle.none], then [BorderSide.none] is returned.
80 81
  ///
  /// The arguments must not be null.
82 83
  static BorderSide merge(BorderSide a, BorderSide b) {
    assert(canMerge(a, b));
84 85
    final bool aIsNone = a.style == BorderStyle.none && a.width == 0.0;
    final bool bIsNone = b.style == BorderStyle.none && b.width == 0.0;
86
    if (aIsNone && bIsNone) {
87
      return BorderSide.none;
88 89
    }
    if (aIsNone) {
90
      return b;
91 92
    }
    if (bIsNone) {
93
      return a;
94
    }
95 96
    assert(a.color == b.color);
    assert(a.style == b.style);
97
    return BorderSide(
98 99
      color: a.color, // == b.color
      width: a.width + b.width,
100
      strokeAlign: math.max(a.strokeAlign, b.strokeAlign),
101 102 103
      style: a.style, // == b.style
    );
  }
104 105 106 107

  /// The color of this side of the border.
  final Color color;

108 109 110
  /// The width of this side of the border, in logical pixels.
  ///
  /// Setting width to 0.0 will result in a hairline border. This means that
111
  /// the border will have the width of one physical pixel. Hairline
112 113 114 115 116
  /// rendering takes shortcuts when the path overlaps a pixel more than once.
  /// This means that it will render faster than otherwise, but it might
  /// double-hit pixels, giving it a slightly darker/lighter result.
  ///
  /// To omit the border entirely, set the [style] to [BorderStyle.none].
117 118 119 120 121 122 123 124 125
  final double width;

  /// The style of this side of the border.
  ///
  /// To omit a side, set [style] to [BorderStyle.none]. This skips
  /// painting the border, but the border still has a [width].
  final BorderStyle style;

  /// A hairline black border that is not rendered.
126
  static const BorderSide none = BorderSide(width: 0.0, style: BorderStyle.none);
127

128 129 130 131 132
  /// The relative position of the stroke on a [BorderSide] in an
  /// [OutlinedBorder] or [Border].
  ///
  /// Values typically range from -1.0 ([strokeAlignInside], inside border,
  /// default) to 1.0 ([strokeAlignOutside], outside border), without any
133
  /// bound constraints (e.g., a value of -2.0 is not typical, but allowed).
134 135 136 137 138 139 140 141 142 143 144 145
  /// A value of 0 ([strokeAlignCenter]) will center the border on the edge
  /// of the widget.
  ///
  /// When set to [strokeAlignInside], the stroke is drawn completely inside
  /// the widget. For [strokeAlignCenter] and [strokeAlignOutside], a property
  /// such as [Container.clipBehavior] can be used in an outside widget to clip
  /// it. If [Container.decoration] has a border, the container may incorporate
  /// [width] as additional padding:
  /// - [strokeAlignInside] provides padding with full [width].
  /// - [strokeAlignCenter] provides padding with half [width].
  /// - [strokeAlignOutside] provides zero padding, as stroke is drawn entirely outside.
  ///
146 147 148 149 150
  /// This property is not honored by [toPaint] (because the [Paint] object
  /// cannot represent it); it is intended that classes that use [BorderSide]
  /// objects implement this property when painting borders by suitably
  /// inflating or deflating their regions.
  ///
151
  /// {@tool dartpad}
152
  /// This example shows an animation of how [strokeAlign] affects the drawing
153 154 155 156 157 158 159 160
  /// when applied to borders of various shapes.
  ///
  /// ** See code in examples/api/lib/painting/borders/border_side.stroke_align.0.dart **
  /// {@end-tool}
  final double strokeAlign;

  /// The border is drawn fully inside of the border path.
  ///
161 162 163
  /// This is a constant for use with [strokeAlign].
  ///
  /// This is the default value for [strokeAlign].
164 165 166 167 168
  static const double strokeAlignInside = -1.0;

  /// The border is drawn on the center of the border path, with half of the
  /// [BorderSide.width] on the inside, and the other half on the outside of
  /// the path.
169 170
  ///
  /// This is a constant for use with [strokeAlign].
171 172 173
  static const double strokeAlignCenter = 0.0;

  /// The border is drawn on the outside of the border path.
174 175
  ///
  /// This is a constant for use with [strokeAlign].
176
  static const double strokeAlignOutside = 1.0;
177

178 179
  /// Creates a copy of this border but with the given fields replaced with the new values.
  BorderSide copyWith({
180 181 182
    Color? color,
    double? width,
    BorderStyle? style,
183
    double? strokeAlign,
184
  }) {
185
    return BorderSide(
186 187
      color: color ?? this.color,
      width: width ?? this.width,
188
      style: style ?? this.style,
189
      strokeAlign: strokeAlign ?? this.strokeAlign,
190 191 192
    );
  }

193 194 195 196 197
  /// Creates a copy of this border side description but with the width scaled
  /// by the factor `t`.
  ///
  /// The `t` argument represents the multiplicand, or the position on the
  /// timeline for an interpolation from nothing to `this`, with 0.0 meaning
198
  /// that the object returned should be the nil variant of this object, 1.0
199 200 201 202 203 204
  /// meaning that no change should be applied, returning `this` (or something
  /// equivalent to `this`), and other values meaning that the object should be
  /// multiplied by `t`. Negative values are treated like zero.
  ///
  /// Since a zero width is normally painted as a hairline width rather than no
  /// border at all, the zero factor is special-cased to instead change the
205
  /// style to [BorderStyle.none].
206 207 208
  ///
  /// Values for `t` are usually obtained from an [Animation<double>], such as
  /// an [AnimationController].
209
  BorderSide scale(double t) {
210
    return BorderSide(
211 212 213
      color: color,
      width: math.max(0.0, width * t),
      style: t <= 0.0 ? BorderStyle.none : style,
214 215 216
    );
  }

217 218 219
  /// Create a [Paint] object that, if used to stroke a line, will draw the line
  /// in this border's style.
  ///
220 221 222
  /// The [strokeAlign] property is not reflected in the [Paint]; consumers must
  /// implement that directly by inflating or deflating their region appropriately.
  ///
223 224 225 226 227 228
  /// Not all borders use this method to paint their border sides. For example,
  /// non-uniform rectangular [Border]s have beveled edges and so paint their
  /// border sides as filled shapes rather than using a stroke.
  Paint toPaint() {
    switch (style) {
      case BorderStyle.solid:
229
        return Paint()
230 231 232 233
          ..color = color
          ..strokeWidth = width
          ..style = PaintingStyle.stroke;
      case BorderStyle.none:
234
        return Paint()
235 236 237 238 239 240
          ..color = const Color(0x00000000)
          ..strokeWidth = 0.0
          ..style = PaintingStyle.stroke;
    }
  }

241 242
  /// Whether the two given [BorderSide]s can be merged using
  /// [BorderSide.merge].
243
  ///
244 245 246 247
  /// Two sides can be merged if one or both are zero-width with
  /// [BorderStyle.none], or if they both have the same color and style.
  ///
  /// The arguments must not be null.
248
  static bool canMerge(BorderSide a, BorderSide b) {
249
    if ((a.style == BorderStyle.none && a.width == 0.0) ||
250
        (b.style == BorderStyle.none && b.width == 0.0)) {
251
      return true;
252
    }
253
    return a.style == b.style
254
        && a.color == b.color;
255 256
  }

257
  /// Linearly interpolate between two border sides.
258 259
  ///
  /// The arguments must not be null.
260
  ///
261
  /// {@macro dart.ui.shadow.lerp}
262
  static BorderSide lerp(BorderSide a, BorderSide b, double t) {
263 264 265
    if (identical(a, b)) {
      return a;
    }
266
    if (t == 0.0) {
267
      return a;
268 269
    }
    if (t == 1.0) {
270
      return b;
271
    }
272
    final double width = ui.lerpDouble(a.width, b.width, t)!;
273
    if (width < 0.0) {
Ian Hickson's avatar
Ian Hickson committed
274
      return BorderSide.none;
275
    }
276
    if (a.style == b.style && a.strokeAlign == b.strokeAlign) {
277
      return BorderSide(
278
        color: Color.lerp(a.color, b.color, t)!,
Ian Hickson's avatar
Ian Hickson committed
279
        width: width,
280
        style: a.style, // == b.style
281
        strokeAlign: a.strokeAlign, // == b.strokeAlign
282 283
      );
    }
284
    final Color colorA, colorB;
285 286 287 288 289 290 291 292 293 294 295 296
    switch (a.style) {
      case BorderStyle.solid:
        colorA = a.color;
      case BorderStyle.none:
        colorA = a.color.withAlpha(0x00);
    }
    switch (b.style) {
      case BorderStyle.solid:
        colorB = b.color;
      case BorderStyle.none:
        colorB = b.color.withAlpha(0x00);
    }
297 298 299
    if (a.strokeAlign != b.strokeAlign) {
      return BorderSide(
        color: Color.lerp(colorA, colorB, t)!,
300 301
        width: width,
        strokeAlign: ui.lerpDouble(a.strokeAlign, b.strokeAlign, t)!,
302 303
      );
    }
304
    return BorderSide(
305
      color: Color.lerp(colorA, colorB, t)!,
Ian Hickson's avatar
Ian Hickson committed
306
      width: width,
307
      strokeAlign: a.strokeAlign, // == b.strokeAlign
308 309 310
    );
  }

311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330
  /// Get the amount of the stroke width that lies inside of the [BorderSide].
  ///
  /// For example, this will return the [width] for a [strokeAlign] of -1, half
  /// the [width] for a [strokeAlign] of 0, and 0 for a [strokeAlign] of 1.
  double get strokeInset => width * (1 - (1 + strokeAlign) / 2);

  /// Get the amount of the stroke width that lies outside of the [BorderSide].
  ///
  /// For example, this will return 0 for a [strokeAlign] of -1, half the
  /// [width] for a [strokeAlign] of 0, and the [width] for a [strokeAlign]
  /// of 1.
  double get strokeOutset => width * (1 + strokeAlign) / 2;

  /// The offset of the stroke, taking into account the stroke alignment.
  ///
  /// For example, this will return the negative [width] of the stroke
  /// for a [strokeAlign] of -1, 0 for a [strokeAlign] of 0, and the
  /// [width] for a [strokeAlign] of -1.
  double get strokeOffset => width * strokeAlign;

331
  @override
332
  bool operator ==(Object other) {
333
    if (identical(this, other)) {
334
      return true;
335 336
    }
    if (other.runtimeType != runtimeType) {
337
      return false;
338
    }
339 340 341
    return other is BorderSide
        && other.color == color
        && other.width == width
342 343
        && other.style == style
        && other.strokeAlign == strokeAlign;
344 345 346
  }

  @override
347
  int get hashCode => Object.hash(color, width, style, strokeAlign);
348 349

  @override
350 351 352 353 354 355 356 357 358
  String toStringShort() => 'BorderSide';

  @override
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
    properties.add(DiagnosticsProperty<Color>('color', color, defaultValue: const Color(0xFF000000)));
    properties.add(DoubleProperty('width', width, defaultValue: 1.0));
    properties.add(DoubleProperty('strokeAlign', strokeAlign, defaultValue: strokeAlignInside));
    properties.add(EnumProperty<BorderStyle>('style', style, defaultValue: BorderStyle.solid));
359
  }
360 361
}

Ian Hickson's avatar
Ian Hickson committed
362 363
/// Base class for shape outlines.
///
364 365
/// This class handles how to add multiple borders together. Subclasses define
/// various shapes, like circles ([CircleBorder]), rounded rectangles
366 367 368
/// ([RoundedRectangleBorder]), continuous rectangles
/// ([ContinuousRectangleBorder]), or beveled rectangles
/// ([BeveledRectangleBorder]).
369 370 371 372 373 374 375
///
/// See also:
///
///  * [ShapeDecoration], which can be used with [DecoratedBox] to show a shape.
///  * [Material] (and many other widgets in the Material library), which takes
///    a [ShapeBorder] to define its shape.
///  * [NotchedShape], which describes a shape with a hole in it.
Ian Hickson's avatar
Ian Hickson committed
376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397
@immutable
abstract class ShapeBorder {
  /// Abstract const constructor. This constructor enables subclasses to provide
  /// const constructors so that they can be used in const expressions.
  const ShapeBorder();

  /// The widths of the sides of this border represented as an [EdgeInsets].
  ///
  /// Specifically, this is the amount by which a rectangle should be inset so
  /// as to avoid painting over any important part of the border. It is the
  /// amount by which additional borders will be inset before they are drawn.
  ///
  /// This can be used, for example, with a [Padding] widget to inset a box by
  /// the size of these borders.
  ///
  /// Shapes that have a fixed ratio regardless of the area on which they are
  /// painted, or that change their rendering based on the size they are given
  /// when painting (for instance [CircleBorder]), will not return valid
  /// [dimensions] information because they cannot know their eventual size when
  /// computing their [dimensions].
  EdgeInsetsGeometry get dimensions;

398
  /// Attempts to create a new object that represents the amalgamation of `this`
Ian Hickson's avatar
Ian Hickson committed
399 400 401 402 403 404 405 406 407 408
  /// border and the `other` border.
  ///
  /// If the type of the other border isn't known, or the given instance cannot
  /// be reasonably added to this instance, then this should return null.
  ///
  /// This method is used by the [operator +] implementation.
  ///
  /// The `reversed` argument is true if this object was the right operand of
  /// the `+` operator, and false if it was the left operand.
  @protected
409
  ShapeBorder? add(ShapeBorder other, { bool reversed = false }) => null;
Ian Hickson's avatar
Ian Hickson committed
410 411 412 413 414 415 416 417 418 419

  /// Creates a new border consisting of the two borders on either side of the
  /// operator.
  ///
  /// If the borders belong to classes that know how to add themselves, then
  /// this results in a new border that represents the intelligent addition of
  /// those two borders (see [add]). Otherwise, an object is returned that
  /// merely paints the two borders sequentially, with the left hand operand on
  /// the inside and the right hand operand on the outside.
  ShapeBorder operator +(ShapeBorder other) {
420
    return add(other) ?? other.add(this, reversed: true) ?? _CompoundBorder(<ShapeBorder>[other, this]);
Ian Hickson's avatar
Ian Hickson committed
421 422
  }

423 424 425 426 427 428 429 430
  /// Creates a copy of this border, scaled by the factor `t`.
  ///
  /// Typically this means scaling the width of the border's side, but it can
  /// also include scaling other artifacts of the border, e.g. the border radius
  /// of a [RoundedRectangleBorder].
  ///
  /// The `t` argument represents the multiplicand, or the position on the
  /// timeline for an interpolation from nothing to `this`, with 0.0 meaning
431
  /// that the object returned should be the nil variant of this object, 1.0
432 433 434 435 436 437 438 439 440 441 442 443 444
  /// meaning that no change should be applied, returning `this` (or something
  /// equivalent to `this`), and other values meaning that the object should be
  /// multiplied by `t`. Negative values are allowed but may be meaningless
  /// (they correspond to extrapolating the interpolation from this object to
  /// nothing, and going beyond nothing)
  ///
  /// Values for `t` are usually obtained from an [Animation<double>], such as
  /// an [AnimationController].
  ///
  /// See also:
  ///
  ///  * [BorderSide.scale], which most [ShapeBorder] subclasses defer to for
  ///    the actual computation.
Ian Hickson's avatar
Ian Hickson committed
445 446
  ShapeBorder scale(double t);

447 448
  /// Linearly interpolates from another [ShapeBorder] (possibly of another
  /// class) to `this`.
Ian Hickson's avatar
Ian Hickson committed
449 450 451 452 453 454 455 456
  ///
  /// When implementing this method in subclasses, return null if this class
  /// cannot interpolate from `a`. In that case, [lerp] will try `a`'s [lerpTo]
  /// method instead. If `a` is null, this must not return null.
  ///
  /// The base class implementation handles the case of `a` being null by
  /// deferring to [scale].
  ///
457 458 459 460 461 462 463 464 465 466 467 468 469
  /// The `t` argument represents position on the timeline, with 0.0 meaning
  /// that the interpolation has not started, returning `a` (or something
  /// equivalent to `a`), 1.0 meaning that the interpolation has finished,
  /// returning `this` (or something equivalent to `this`), and values in
  /// between meaning that the interpolation is at the relevant point on the
  /// timeline between `a` and `this`. The interpolation can be extrapolated
  /// beyond 0.0 and 1.0, so negative values and values greater than 1.0 are
  /// valid (and can easily be generated by curves such as
  /// [Curves.elasticInOut]).
  ///
  /// Values for `t` are usually obtained from an [Animation<double>], such as
  /// an [AnimationController].
  ///
Ian Hickson's avatar
Ian Hickson committed
470 471
  /// Instead of calling this directly, use [ShapeBorder.lerp].
  @protected
472
  ShapeBorder? lerpFrom(ShapeBorder? a, double t) {
473
    if (a == null) {
Ian Hickson's avatar
Ian Hickson committed
474
      return scale(t);
475
    }
Ian Hickson's avatar
Ian Hickson committed
476 477 478
    return null;
  }

479 480
  /// Linearly interpolates from `this` to another [ShapeBorder] (possibly of
  /// another class).
Ian Hickson's avatar
Ian Hickson committed
481 482 483 484 485 486 487 488 489 490
  ///
  /// This is called if `b`'s [lerpTo] did not know how to handle this class.
  ///
  /// When implementing this method in subclasses, return null if this class
  /// cannot interpolate from `b`. In that case, [lerp] will apply a default
  /// behavior instead. If `b` is null, this must not return null.
  ///
  /// The base class implementation handles the case of `b` being null by
  /// deferring to [scale].
  ///
491 492 493 494 495 496 497 498 499 500 501 502
  /// The `t` argument represents position on the timeline, with 0.0 meaning
  /// that the interpolation has not started, returning `this` (or something
  /// equivalent to `this`), 1.0 meaning that the interpolation has finished,
  /// returning `b` (or something equivalent to `b`), and values in between
  /// meaning that the interpolation is at the relevant point on the timeline
  /// between `this` and `b`. The interpolation can be extrapolated beyond 0.0
  /// and 1.0, so negative values and values greater than 1.0 are valid (and can
  /// easily be generated by curves such as [Curves.elasticInOut]).
  ///
  /// Values for `t` are usually obtained from an [Animation<double>], such as
  /// an [AnimationController].
  ///
Ian Hickson's avatar
Ian Hickson committed
503 504
  /// Instead of calling this directly, use [ShapeBorder.lerp].
  @protected
505
  ShapeBorder? lerpTo(ShapeBorder? b, double t) {
506
    if (b == null) {
Ian Hickson's avatar
Ian Hickson committed
507
      return scale(1.0 - t);
508
    }
Ian Hickson's avatar
Ian Hickson committed
509 510 511
    return null;
  }

512 513 514 515 516 517 518
  /// Linearly interpolates between two [ShapeBorder]s.
  ///
  /// This defers to `b`'s [lerpTo] function if `b` is not null. If `b` is
  /// null or if its [lerpTo] returns null, it uses `a`'s [lerpFrom]
  /// function instead. If both return null, it returns `a` before `t=0.5`
  /// and `b` after `t=0.5`.
  ///
519
  /// {@macro dart.ui.shadow.lerp}
520
  static ShapeBorder? lerp(ShapeBorder? a, ShapeBorder? b, double t) {
521 522 523
    if (identical(a, b)) {
      return a;
    }
524
    ShapeBorder? result;
525
    if (b != null) {
526
      result = b.lerpFrom(a, t);
527 528
    }
    if (result == null && a != null) {
529
      result = a.lerpTo(b, t);
530
    }
531
    return result ?? (t < 0.5 ? a : b);
Ian Hickson's avatar
Ian Hickson committed
532 533 534 535 536 537 538 539 540 541 542 543
  }

  /// Create a [Path] that describes the outer edge of the border.
  ///
  /// This path must not cross the path given by [getInnerPath] for the same
  /// [Rect].
  ///
  /// To obtain a [Path] that describes the area of the border itself, set the
  /// [Path.fillType] of the returned object to [PathFillType.evenOdd], and add
  /// to this object the path returned from [getInnerPath] (using
  /// [Path.addPath]).
  ///
544
  /// The `textDirection` argument must be provided non-null if the border
Ian Hickson's avatar
Ian Hickson committed
545 546 547 548 549 550 551 552
  /// has a text direction dependency (for example if it is expressed in terms
  /// of "start" and "end" instead of "left" and "right"). It may be null if
  /// the border will not need the text direction to paint itself.
  ///
  /// See also:
  ///
  ///  * [getInnerPath], which creates the path for the inner edge.
  ///  * [Path.contains], which can tell if an [Offset] is within a [Path].
553
  Path getOuterPath(Rect rect, { TextDirection? textDirection });
Ian Hickson's avatar
Ian Hickson committed
554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573

  /// Create a [Path] that describes the inner edge of the border.
  ///
  /// This path must not cross the path given by [getOuterPath] for the same
  /// [Rect].
  ///
  /// To obtain a [Path] that describes the area of the border itself, set the
  /// [Path.fillType] of the returned object to [PathFillType.evenOdd], and add
  /// to this object the path returned from [getOuterPath] (using
  /// [Path.addPath]).
  ///
  /// The `textDirection` argument must be provided and non-null if the border
  /// has a text direction dependency (for example if it is expressed in terms
  /// of "start" and "end" instead of "left" and "right"). It may be null if
  /// the border will not need the text direction to paint itself.
  ///
  /// See also:
  ///
  ///  * [getOuterPath], which creates the path for the outer edge.
  ///  * [Path.contains], which can tell if an [Offset] is within a [Path].
574
  Path getInnerPath(Rect rect, { TextDirection? textDirection });
Ian Hickson's avatar
Ian Hickson committed
575

576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647
  /// Paint a canvas with the appropriate shape.
  ///
  /// On [ShapeBorder] subclasses whose [preferPaintInterior] method returns
  /// true, this should be faster than using [Canvas.drawPath] with the path
  /// provided by [getOuterPath]. (If [preferPaintInterior] returns false,
  /// then this method asserts in debug mode and does nothing in release mode.)
  ///
  /// Subclasses are expected to implement this method when the [Canvas] API
  /// has a dedicated method to draw the relevant shape. For example,
  /// [CircleBorder] uses this to call [Canvas.drawCircle], and
  /// [RoundedRectangleBorder] uses this to call [Canvas.drawRRect].
  ///
  /// Subclasses that implement this must ensure that calling [paintInterior]
  /// is semantically equivalent to (i.e. renders the same pixels as) calling
  /// [Canvas.drawPath] with the same [Paint] and the [Path] returned from
  /// [getOuterPath], and must also override [preferPaintInterior] to
  /// return true.
  ///
  /// For example, a shape that draws a rectangle might implement
  /// [getOuterPath], [paintInterior], and [preferPaintInterior] as follows:
  ///
  /// ```dart
  /// class RectangleBorder extends OutlinedBorder {
  ///   // ...
  ///
  ///   @override
  ///   Path getOuterPath(Rect rect, { TextDirection? textDirection }) {
  ///    return Path()
  ///      ..addRect(rect);
  ///   }
  ///
  ///   @override
  ///   void paintInterior(Canvas canvas, Rect rect, Paint paint, {TextDirection? textDirection}) {
  ///    canvas.drawRect(rect, paint);
  ///   }
  ///
  ///   @override
  ///   bool get preferPaintInterior => true;
  ///
  ///   // ...
  /// }
  /// ```
  ///
  /// When a shape can only be drawn using path, [preferPaintInterior] must
  /// return false. In that case, classes such as [ShapeDecoration] will cache
  /// the path from [getOuterPath] and call [Canvas.drawPath] directly.
  void paintInterior(Canvas canvas, Rect rect, Paint paint, {TextDirection? textDirection}) {
    assert(!preferPaintInterior, '$runtimeType.preferPaintInterior returns true but $runtimeType.paintInterior is not implemented.');
    assert(false, '$runtimeType.preferPaintInterior returns false, so it is an error to call its paintInterior method.');
  }

  /// Reports whether [paintInterior] is implemented.
  ///
  /// Classes such as [ShapeDecoration] prefer to use [paintInterior] if this
  /// getter returns true. This is intended to enable faster painting; instead
  /// of computing a shape using [getOuterPath] and then drawing it using
  /// [Canvas.drawPath], the path can be drawn directly to the [Canvas] using
  /// dedicated methods such as [Canvas.drawRect] or [Canvas.drawCircle].
  ///
  /// By default, this getter returns false.
  ///
  /// Subclasses that implement [paintInterior] should override this to return
  /// true. Subclasses should only override [paintInterior] if doing so enables
  /// faster rendering than is possible with [Canvas.drawPath] (so, in
  /// particular, subclasses should not call [Canvas.drawPath] in
  /// [paintInterior]).
  ///
  /// See also:
  ///
  ///  * [paintInterior], whose API documentation has an example implementation.
  bool get preferPaintInterior => false;

Ian Hickson's avatar
Ian Hickson committed
648 649 650 651 652 653
  /// Paints the border within the given [Rect] on the given [Canvas].
  ///
  /// The `textDirection` argument must be provided and non-null if the border
  /// has a text direction dependency (for example if it is expressed in terms
  /// of "start" and "end" instead of "left" and "right"). It may be null if
  /// the border will not need the text direction to paint itself.
654
  void paint(Canvas canvas, Rect rect, { TextDirection? textDirection });
Ian Hickson's avatar
Ian Hickson committed
655 656 657

  @override
  String toString() {
658
    return '${objectRuntimeType(this, 'ShapeBorder')}()';
Ian Hickson's avatar
Ian Hickson committed
659 660 661
  }
}

662 663 664 665 666 667 668 669
/// A ShapeBorder that draws an outline with the width and color specified
/// by [side].
@immutable
abstract class OutlinedBorder extends ShapeBorder {
  /// Abstract const constructor. This constructor enables subclasses to provide
  /// const constructors so that they can be used in const expressions.
  ///
  /// The value of [side] must not be null.
670
  const OutlinedBorder({ this.side = BorderSide.none });
671

672 673 674
  @override
  EdgeInsetsGeometry get dimensions => EdgeInsets.all(math.max(side.strokeInset, 0));

675 676 677 678 679 680 681 682
  /// The border outline's color and weight.
  ///
  /// If [side] is [BorderSide.none], which is the default, an outline is not drawn.
  /// Otherwise the outline is centered over the shape's boundary.
  final BorderSide side;

  /// Returns a copy of this OutlinedBorder that draws its outline with the
  /// specified [side], if [side] is non-null.
683
  OutlinedBorder copyWith({ BorderSide? side });
684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712

  @override
  ShapeBorder scale(double t);

  @override
  ShapeBorder? lerpFrom(ShapeBorder? a, double t) {
    if (a == null) {
      return scale(t);
    }
    return null;
  }

  @override
  ShapeBorder? lerpTo(ShapeBorder? b, double t) {
    if (b == null) {
      return scale(1.0 - t);
    }
    return null;
  }

  /// Linearly interpolates between two [OutlinedBorder]s.
  ///
  /// This defers to `b`'s [lerpTo] function if `b` is not null. If `b` is
  /// null or if its [lerpTo] returns null, it uses `a`'s [lerpFrom]
  /// function instead. If both return null, it returns `a` before `t=0.5`
  /// and `b` after `t=0.5`.
  ///
  /// {@macro dart.ui.shadow.lerp}
  static OutlinedBorder? lerp(OutlinedBorder? a, OutlinedBorder? b, double t) {
713 714 715
    if (identical(a, b)) {
      return a;
    }
716 717 718 719 720 721 722 723 724
    ShapeBorder? result;
    if (b != null) {
      result = b.lerpFrom(a, t);
    }
    if (result == null && a != null) {
      result = a.lerpTo(b, t);
    }
    return result as OutlinedBorder? ?? (t < 0.5 ? a : b);
  }
725 726
}

Ian Hickson's avatar
Ian Hickson committed
727 728 729 730
/// Represents the addition of two otherwise-incompatible borders.
///
/// The borders are listed from the outside to the inside.
class _CompoundBorder extends ShapeBorder {
731
  _CompoundBorder(this.borders)
732
    : assert(borders.length >= 2),
733
      assert(!borders.any((ShapeBorder border) => border is _CompoundBorder));
Ian Hickson's avatar
Ian Hickson committed
734 735 736 737 738 739 740 741 742 743 744 745 746 747

  final List<ShapeBorder> borders;

  @override
  EdgeInsetsGeometry get dimensions {
    return borders.fold<EdgeInsetsGeometry>(
      EdgeInsets.zero,
      (EdgeInsetsGeometry previousValue, ShapeBorder border) {
        return previousValue.add(border.dimensions);
      },
    );
  }

  @override
748
  ShapeBorder add(ShapeBorder other, { bool reversed = false }) {
Ian Hickson's avatar
Ian Hickson committed
749 750 751 752 753 754 755 756 757 758
    // This wraps the list of borders with "other", or, if "reversed" is true,
    // wraps "other" with the list of borders.
    // If "reversed" is false, "other" should end up being at the start of the
    // list, otherwise, if "reversed" is true, it should end up at the end.
    // First, see if we can merge the new adjacent borders.
    if (other is! _CompoundBorder) {
      // Here, "ours" is the border at the side where we're adding the new
      // border, and "merged" is the result of attempting to merge it with the
      // new border. If it's null, it couldn't be merged.
      final ShapeBorder ours = reversed ? borders.last : borders.first;
759
      final ShapeBorder? merged = ours.add(other, reversed: reversed)
Ian Hickson's avatar
Ian Hickson committed
760 761
                             ?? other.add(ours, reversed: !reversed);
      if (merged != null) {
762
        final List<ShapeBorder> result = <ShapeBorder>[...borders];
Ian Hickson's avatar
Ian Hickson committed
763
        result[reversed ? result.length - 1 : 0] = merged;
764
        return _CompoundBorder(result);
Ian Hickson's avatar
Ian Hickson committed
765 766 767
      }
    }
    // We can't, so fall back to just adding the new border to the list.
768 769 770 771 772 773
    final List<ShapeBorder> mergedBorders = <ShapeBorder>[
      if (reversed) ...borders,
      if (other is _CompoundBorder) ...other.borders
      else other,
      if (!reversed) ...borders,
    ];
774
    return _CompoundBorder(mergedBorders);
Ian Hickson's avatar
Ian Hickson committed
775 776 777 778
  }

  @override
  ShapeBorder scale(double t) {
779
    return _CompoundBorder(
780
      borders.map<ShapeBorder>((ShapeBorder border) => border.scale(t)).toList(),
Ian Hickson's avatar
Ian Hickson committed
781 782 783 784
    );
  }

  @override
785
  ShapeBorder? lerpFrom(ShapeBorder? a, double t) {
Ian Hickson's avatar
Ian Hickson committed
786 787 788 789
    return _CompoundBorder.lerp(a, this, t);
  }

  @override
790
  ShapeBorder? lerpTo(ShapeBorder? b, double t) {
Ian Hickson's avatar
Ian Hickson committed
791 792 793
    return _CompoundBorder.lerp(this, b, t);
  }

794
  static _CompoundBorder lerp(ShapeBorder? a, ShapeBorder? b, double t) {
Ian Hickson's avatar
Ian Hickson committed
795
    assert(a is _CompoundBorder || b is _CompoundBorder); // Not really necessary, but all call sites currently intend this.
796 797
    final List<ShapeBorder?> aList = a is _CompoundBorder ? a.borders : <ShapeBorder?>[a];
    final List<ShapeBorder?> bList = b is _CompoundBorder ? b.borders : <ShapeBorder?>[b];
Ian Hickson's avatar
Ian Hickson committed
798 799 800
    final List<ShapeBorder> results = <ShapeBorder>[];
    final int length = math.max(aList.length, bList.length);
    for (int index = 0; index < length; index += 1) {
801 802
      final ShapeBorder? localA = index < aList.length ? aList[index] : null;
      final ShapeBorder? localB = index < bList.length ? bList[index] : null;
Ian Hickson's avatar
Ian Hickson committed
803
      if (localA != null && localB != null) {
804
        final ShapeBorder? localResult = localA.lerpTo(localB, t) ?? localB.lerpFrom(localA, t);
Ian Hickson's avatar
Ian Hickson committed
805 806 807 808 809 810 811 812 813
        if (localResult != null) {
          results.add(localResult);
          continue;
        }
      }
      // If we're changing from one shape to another, make sure the shape that is coming in
      // is inserted before the shape that is going away, so that the outer path changes to
      // the new border earlier rather than later. (This affects, among other things, where
      // the ShapeDecoration class puts its background.)
814
      if (localB != null) {
Ian Hickson's avatar
Ian Hickson committed
815
        results.add(localB.scale(t));
816 817
      }
      if (localA != null) {
Ian Hickson's avatar
Ian Hickson committed
818
        results.add(localA.scale(1.0 - t));
819
      }
Ian Hickson's avatar
Ian Hickson committed
820
    }
821
    return _CompoundBorder(results);
Ian Hickson's avatar
Ian Hickson committed
822 823 824
  }

  @override
825
  Path getInnerPath(Rect rect, { TextDirection? textDirection }) {
826
    for (int index = 0; index < borders.length - 1; index += 1) {
Ian Hickson's avatar
Ian Hickson committed
827
      rect = borders[index].dimensions.resolve(textDirection).deflateRect(rect);
828
    }
829
    return borders.last.getInnerPath(rect, textDirection: textDirection);
Ian Hickson's avatar
Ian Hickson committed
830 831 832
  }

  @override
833
  Path getOuterPath(Rect rect, { TextDirection? textDirection }) {
834
    return borders.first.getOuterPath(rect, textDirection: textDirection);
Ian Hickson's avatar
Ian Hickson committed
835 836
  }

837 838 839 840 841 842
  @override
  void paintInterior(Canvas canvas, Rect rect, Paint paint, { TextDirection? textDirection }) {
    borders.first.paintInterior(canvas, rect, paint, textDirection: textDirection);
  }

  @override
843
  bool get preferPaintInterior => borders.every((ShapeBorder border) => border.preferPaintInterior);
844

Ian Hickson's avatar
Ian Hickson committed
845
  @override
846
  void paint(Canvas canvas, Rect rect, { TextDirection? textDirection }) {
847
    for (final ShapeBorder border in borders) {
Ian Hickson's avatar
Ian Hickson committed
848 849 850 851 852 853
      border.paint(canvas, rect, textDirection: textDirection);
      rect = border.dimensions.resolve(textDirection).deflateRect(rect);
    }
  }

  @override
854
  bool operator ==(Object other) {
855
    if (identical(this, other)) {
Ian Hickson's avatar
Ian Hickson committed
856
      return true;
857 858
    }
    if (other.runtimeType != runtimeType) {
Ian Hickson's avatar
Ian Hickson committed
859
      return false;
860
    }
861 862
    return other is _CompoundBorder
        && listEquals<ShapeBorder>(other.borders, borders);
Ian Hickson's avatar
Ian Hickson committed
863 864 865
  }

  @override
866
  int get hashCode => Object.hashAll(borders);
Ian Hickson's avatar
Ian Hickson committed
867 868 869 870 871 872 873 874 875 876 877

  @override
  String toString() {
    // We list them in reverse order because when adding two borders they end up
    // in the list in the opposite order of what the source looks like: a + b =>
    // [b, a]. We do this to make the painting code more optimal, and most of
    // the rest of the code doesn't care, except toString() (for debugging).
    return borders.reversed.map<String>((ShapeBorder border) => border.toString()).join(' + ');
  }
}

878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894
/// Paints a border around the given rectangle on the canvas.
///
/// The four sides can be independently specified. They are painted in the order
/// top, right, bottom, left. This is only notable if the widths of the borders
/// and the size of the given rectangle are such that the border sides will
/// overlap each other. No effort is made to optimize the rendering of uniform
/// borders (where all the borders have the same configuration); to render a
/// uniform border, consider using [Canvas.drawRect] directly.
///
/// The arguments must not be null.
///
/// See also:
///
///  * [paintImage], which paints an image in a rectangle on a canvas.
///  * [Border], which uses this function to paint its border when the border is
///    not uniform.
///  * [BoxDecoration], which describes its border using the [Border] class.
895 896 897
void paintBorder(
  Canvas canvas,
  Rect rect, {
898 899 900 901
  BorderSide top = BorderSide.none,
  BorderSide right = BorderSide.none,
  BorderSide bottom = BorderSide.none,
  BorderSide left = BorderSide.none,
902 903 904 905 906
}) {

  // We draw the borders as filled shapes, unless the borders are hairline
  // borders, in which case we use PaintingStyle.stroke, with the stroke width
  // specified here.
907
  final Paint paint = Paint()
908 909
    ..strokeWidth = 0.0;

910
  final Path path = Path();
911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982

  switch (top.style) {
    case BorderStyle.solid:
      paint.color = top.color;
      path.reset();
      path.moveTo(rect.left, rect.top);
      path.lineTo(rect.right, rect.top);
      if (top.width == 0.0) {
        paint.style = PaintingStyle.stroke;
      } else {
        paint.style = PaintingStyle.fill;
        path.lineTo(rect.right - right.width, rect.top + top.width);
        path.lineTo(rect.left + left.width, rect.top + top.width);
      }
      canvas.drawPath(path, paint);
    case BorderStyle.none:
      break;
  }

  switch (right.style) {
    case BorderStyle.solid:
      paint.color = right.color;
      path.reset();
      path.moveTo(rect.right, rect.top);
      path.lineTo(rect.right, rect.bottom);
      if (right.width == 0.0) {
        paint.style = PaintingStyle.stroke;
      } else {
        paint.style = PaintingStyle.fill;
        path.lineTo(rect.right - right.width, rect.bottom - bottom.width);
        path.lineTo(rect.right - right.width, rect.top + top.width);
      }
      canvas.drawPath(path, paint);
    case BorderStyle.none:
      break;
  }

  switch (bottom.style) {
    case BorderStyle.solid:
      paint.color = bottom.color;
      path.reset();
      path.moveTo(rect.right, rect.bottom);
      path.lineTo(rect.left, rect.bottom);
      if (bottom.width == 0.0) {
        paint.style = PaintingStyle.stroke;
      } else {
        paint.style = PaintingStyle.fill;
        path.lineTo(rect.left + left.width, rect.bottom - bottom.width);
        path.lineTo(rect.right - right.width, rect.bottom - bottom.width);
      }
      canvas.drawPath(path, paint);
    case BorderStyle.none:
      break;
  }

  switch (left.style) {
    case BorderStyle.solid:
      paint.color = left.color;
      path.reset();
      path.moveTo(rect.left, rect.bottom);
      path.lineTo(rect.left, rect.top);
      if (left.width == 0.0) {
        paint.style = PaintingStyle.stroke;
      } else {
        paint.style = PaintingStyle.fill;
        path.lineTo(rect.left + left.width, rect.top + top.width);
        path.lineTo(rect.left + left.width, rect.bottom - bottom.width);
      }
      canvas.drawPath(path, paint);
    case BorderStyle.none:
      break;
  }
983
}