box_border.dart 32.3 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.

Ian Hickson's avatar
Ian Hickson committed
5 6
import 'package:flutter/foundation.dart';

7 8 9 10 11
import 'basic_types.dart';
import 'border_radius.dart';
import 'borders.dart';
import 'edge_insets.dart';

12
// Examples can assume:
13
// late BuildContext context;
14

15
/// The shape to use when rendering a [Border] or [BoxDecoration].
16 17 18 19 20
///
/// Consider using [ShapeBorder] subclasses directly (with [ShapeDecoration]),
/// instead of using [BoxShape] and [Border], if the shapes will need to be
/// interpolated or animated. The [Border] class cannot interpolate between
/// different shapes.
21 22 23 24
enum BoxShape {
  /// An axis-aligned, 2D rectangle. May have rounded corners (described by a
  /// [BorderRadius]). The edges of the rectangle will match the edges of the box
  /// into which the [Border] or [BoxDecoration] is painted.
25 26 27 28
  ///
  /// See also:
  ///
  ///  * [RoundedRectangleBorder], the equivalent [ShapeBorder].
29 30 31 32 33 34
  rectangle,

  /// A circle centered in the middle of the box into which the [Border] or
  /// [BoxDecoration] is painted. The diameter of the circle is the shortest
  /// dimension of the box, either the width or the height, such that the circle
  /// touches the edges of the box.
35 36 37 38
  ///
  /// See also:
  ///
  ///  * [CircleBorder], the equivalent [ShapeBorder].
39
  circle,
40 41

  // Don't add more, instead create a new ShapeBorder.
42 43
}

44
/// Base class for box borders that can paint as rectangles, circles, or rounded
Ian Hickson's avatar
Ian Hickson committed
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
/// rectangles.
///
/// This class is extended by [Border] and [BorderDirectional] to provide
/// concrete versions of four-sided borders using different conventions for
/// specifying the sides.
///
/// The only API difference that this class introduces over [ShapeBorder] is
/// that its [paint] method takes additional arguments.
///
/// See also:
///
///  * [BorderSide], which is used to describe each side of the box.
///  * [RoundedRectangleBorder], another way of describing a box's border.
///  * [CircleBorder], another way of describing a circle border.
///  * [BoxDecoration], which uses a [BoxBorder] to describe its borders.
abstract class BoxBorder extends ShapeBorder {
  /// Abstract const constructor. This constructor enables subclasses to provide
  /// const constructors so that they can be used in const expressions.
  const BoxBorder();

65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
  /// The top side of this border.
  ///
  /// This getter is available on both [Border] and [BorderDirectional]. If
  /// [isUniform] is true, then this is the same style as all the other sides.
  BorderSide get top;

  /// The bottom side of this border.
  BorderSide get bottom;

  /// Whether all four sides of the border are identical. Uniform borders are
  /// typically more efficient to paint.
  ///
  /// A uniform border by definition has no text direction dependency and
  /// therefore could be expressed as a [Border], even if it is currently a
  /// [BorderDirectional]. A uniform border can also be expressed as a
  /// [RoundedRectangleBorder].
  bool get isUniform;

Ian Hickson's avatar
Ian Hickson committed
83
  // We override this to tighten the return value, so that callers can assume
84
  // that we'll return a [BoxBorder].
Ian Hickson's avatar
Ian Hickson committed
85
  @override
86
  BoxBorder? add(ShapeBorder other, { bool reversed = false }) => null;
Ian Hickson's avatar
Ian Hickson committed
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102

  /// Linearly interpolate between two borders.
  ///
  /// If a border is null, it is treated as having four [BorderSide.none]
  /// borders.
  ///
  /// This supports interpolating between [Border] and [BorderDirectional]
  /// objects. If both objects are different types but both have sides on one or
  /// both of their lateral edges (the two sides that aren't the top and bottom)
  /// other than [BorderSide.none], then the sides are interpolated by reducing
  /// `a`'s lateral edges to [BorderSide.none] over the first half of the
  /// animation, and then bringing `b`'s lateral edges _from_ [BorderSide.none]
  /// over the second half of the animation.
  ///
  /// For a more flexible approach, consider [ShapeBorder.lerp], which would
  /// instead [add] the two sets of sides and interpolate them simultaneously.
103
  ///
104
  /// {@macro dart.ui.shadow.lerp}
105
  static BoxBorder? lerp(BoxBorder? a, BoxBorder? b, double t) {
106
    assert(t != null);
107
    if ((a is Border?) && (b is Border?)) {
108
      return Border.lerp(a, b, t);
109 110
    }
    if ((a is BorderDirectional?) && (b is BorderDirectional?)) {
111
      return BorderDirectional.lerp(a, b, t);
112
    }
Ian Hickson's avatar
Ian Hickson committed
113 114 115 116 117 118 119 120 121 122
    if (b is Border && a is BorderDirectional) {
      final BoxBorder c = b;
      b = a;
      a = c;
      t = 1.0 - t;
      // fall through to next case
    }
    if (a is Border && b is BorderDirectional) {
      if (b.start == BorderSide.none && b.end == BorderSide.none) {
        // The fact that b is a BorderDirectional really doesn't matter, it turns out.
123
        return Border(
Ian Hickson's avatar
Ian Hickson committed
124 125 126 127 128 129 130 131
          top: BorderSide.lerp(a.top, b.top, t),
          right: BorderSide.lerp(a.right, BorderSide.none, t),
          bottom: BorderSide.lerp(a.bottom, b.bottom, t),
          left: BorderSide.lerp(a.left, BorderSide.none, t),
        );
      }
      if (a.left == BorderSide.none && a.right == BorderSide.none) {
        // The fact that a is a Border really doesn't matter, it turns out.
132
        return BorderDirectional(
Ian Hickson's avatar
Ian Hickson committed
133 134 135 136 137 138 139 140 141 142
          top: BorderSide.lerp(a.top, b.top, t),
          start: BorderSide.lerp(BorderSide.none, b.start, t),
          end: BorderSide.lerp(BorderSide.none, b.end, t),
          bottom: BorderSide.lerp(a.bottom, b.bottom, t),
        );
      }
      // Since we have to swap a visual border for a directional one,
      // we speed up the horizontal sides' transitions and switch from
      // one mode to the other at t=0.5.
      if (t < 0.5) {
143
        return Border(
Ian Hickson's avatar
Ian Hickson committed
144 145 146 147 148 149
          top: BorderSide.lerp(a.top, b.top, t),
          right: BorderSide.lerp(a.right, BorderSide.none, t * 2.0),
          bottom: BorderSide.lerp(a.bottom, b.bottom, t),
          left: BorderSide.lerp(a.left, BorderSide.none, t * 2.0),
        );
      }
150
      return BorderDirectional(
Ian Hickson's avatar
Ian Hickson committed
151 152 153 154 155 156
        top: BorderSide.lerp(a.top, b.top, t),
        start: BorderSide.lerp(BorderSide.none, b.start, (t - 0.5) * 2.0),
        end: BorderSide.lerp(BorderSide.none, b.end, (t - 0.5) * 2.0),
        bottom: BorderSide.lerp(a.bottom, b.bottom, t),
      );
    }
157 158 159 160 161 162
    throw FlutterError.fromParts(<DiagnosticsNode>[
      ErrorSummary('BoxBorder.lerp can only interpolate Border and BorderDirectional classes.'),
      ErrorDescription(
        'BoxBorder.lerp() was called with two objects of type ${a.runtimeType} and ${b.runtimeType}:\n'
        '  $a\n'
        '  $b\n'
163
        'However, only Border and BorderDirectional classes are supported by this method.',
164 165 166
      ),
      ErrorHint('For a more general interpolation method, consider using ShapeBorder.lerp instead.'),
    ]);
Ian Hickson's avatar
Ian Hickson committed
167 168 169
  }

  @override
170
  Path getInnerPath(Rect rect, { TextDirection? textDirection }) {
Ian Hickson's avatar
Ian Hickson committed
171
    assert(textDirection != null, 'The textDirection argument to $runtimeType.getInnerPath must not be null.');
172
    return Path()
Ian Hickson's avatar
Ian Hickson committed
173 174 175 176
      ..addRect(dimensions.resolve(textDirection).deflateRect(rect));
  }

  @override
177
  Path getOuterPath(Rect rect, { TextDirection? textDirection }) {
Ian Hickson's avatar
Ian Hickson committed
178
    assert(textDirection != null, 'The textDirection argument to $runtimeType.getOuterPath must not be null.');
179
    return Path()
Ian Hickson's avatar
Ian Hickson committed
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
      ..addRect(rect);
  }

  /// Paints the border within the given [Rect] on the given [Canvas].
  ///
  /// This is an extension of the [ShapeBorder.paint] method. It allows
  /// [BoxBorder] borders to be applied to different [BoxShape]s and with
  /// different [borderRadius] parameters, without changing the [BoxBorder]
  /// object itself.
  ///
  /// The `shape` argument specifies the [BoxShape] to draw the border on.
  ///
  /// If the `shape` is specifies a rectangular box shape
  /// ([BoxShape.rectangle]), then the `borderRadius` argument describes the
  /// corners of the rectangle.
  ///
  /// The [getInnerPath] and [getOuterPath] methods do not know about the
  /// `shape` and `borderRadius` arguments.
  ///
  /// See also:
  ///
  ///  * [paintBorder], which is used if the border is not uniform.
  @override
203 204 205
  void paint(
    Canvas canvas,
    Rect rect, {
206
    TextDirection? textDirection,
207
    BoxShape shape = BoxShape.rectangle,
208
    BorderRadius? borderRadius,
Ian Hickson's avatar
Ian Hickson committed
209 210 211 212
  });

  static void _paintUniformBorderWithRadius(Canvas canvas, Rect rect, BorderSide side, BorderRadius borderRadius) {
    assert(side.style != BorderStyle.none);
213
    final Paint paint = Paint()
Ian Hickson's avatar
Ian Hickson committed
214 215 216 217 218 219
      ..color = side.color;
    final double width = side.width;
    if (width == 0.0) {
      paint
        ..style = PaintingStyle.stroke
        ..strokeWidth = 0.0;
220
      canvas.drawRRect(borderRadius.toRRect(rect), paint);
Ian Hickson's avatar
Ian Hickson committed
221
    } else {
222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
      if (side.strokeAlign == StrokeAlign.inside) {
        final RRect outer = borderRadius.toRRect(rect);
        final RRect inner = outer.deflate(width);
        canvas.drawDRRect(outer, inner, paint);
      } else {
        final Rect inner;
        final Rect outer;
        if (side.strokeAlign == StrokeAlign.center) {
          inner = rect.deflate(width / 2);
          outer = rect.inflate(width / 2);
        } else {
          inner = rect;
          outer = rect.inflate(width);
        }
        canvas.drawDRRect(borderRadius.toRRect(outer), borderRadius.toRRect(inner), paint);
      }
Ian Hickson's avatar
Ian Hickson committed
238 239 240 241 242 243 244
    }
  }

  static void _paintUniformBorderWithCircle(Canvas canvas, Rect rect, BorderSide side) {
    assert(side.style != BorderStyle.none);
    final double width = side.width;
    final Paint paint = side.toPaint();
245 246 247 248 249 250 251 252 253 254 255 256
    final double radius;
    switch (side.strokeAlign) {
      case StrokeAlign.inside:
        radius = (rect.shortestSide - width) / 2.0;
        break;
      case StrokeAlign.center:
        radius = rect.shortestSide / 2.0;
        break;
      case StrokeAlign.outside:
        radius = (rect.shortestSide + width) / 2.0;
        break;
    }
Ian Hickson's avatar
Ian Hickson committed
257 258 259 260 261 262 263
    canvas.drawCircle(rect.center, radius, paint);
  }

  static void _paintUniformBorderWithRectangle(Canvas canvas, Rect rect, BorderSide side) {
    assert(side.style != BorderStyle.none);
    final double width = side.width;
    final Paint paint = side.toPaint();
264 265 266 267 268 269 270 271 272 273 274 275 276 277
    final Rect rectToBeDrawn;
    switch (side.strokeAlign) {
      case StrokeAlign.inside:
        rectToBeDrawn = rect.deflate(width / 2.0);
        break;
      case StrokeAlign.center:
        rectToBeDrawn = rect;
        break;
      case StrokeAlign.outside:
        rectToBeDrawn = rect.inflate(width / 2.0);
        break;
    }

    canvas.drawRect(rectToBeDrawn, paint);
Ian Hickson's avatar
Ian Hickson committed
278 279 280 281
  }
}

/// A border of a box, comprised of four sides: top, right, bottom, left.
282 283 284
///
/// The sides are represented by [BorderSide] objects.
///
285
/// {@tool snippet}
286 287 288 289
///
/// All four borders the same, two-pixel wide solid white:
///
/// ```dart
290
/// Border.all(width: 2.0, color: const Color(0xFFFFFFFF))
291
/// ```
292
/// {@end-tool}
293
/// {@tool snippet}
294
///
295
/// The border for a Material Design divider:
296 297
///
/// ```dart
298
/// Border(bottom: BorderSide(color: Theme.of(context).dividerColor))
299
/// ```
300
/// {@end-tool}
301
/// {@tool snippet}
302 303 304 305
///
/// A 1990s-era "OK" button:
///
/// ```dart
306
/// Container(
307
///   decoration: const BoxDecoration(
308
///     border: Border(
309 310 311 312
///       top: BorderSide(color: Color(0xFFFFFFFF)),
///       left: BorderSide(color: Color(0xFFFFFFFF)),
///       right: BorderSide(),
///       bottom: BorderSide(),
313 314
///     ),
///   ),
315
///   child: Container(
316 317
///     padding: const EdgeInsets.symmetric(horizontal: 20.0, vertical: 2.0),
///     decoration: const BoxDecoration(
318
///       border: Border(
319 320 321 322
///         top: BorderSide(color: Color(0xFFDFDFDF)),
///         left: BorderSide(color: Color(0xFFDFDFDF)),
///         right: BorderSide(color: Color(0xFF7F7F7F)),
///         bottom: BorderSide(color: Color(0xFF7F7F7F)),
323
///       ),
324
///       color: Color(0xFFBFBFBF),
325 326 327 328
///     ),
///     child: const Text(
///       'OK',
///       textAlign: TextAlign.center,
329
///       style: TextStyle(color: Color(0xFF000000))
330 331 332 333
///     ),
///   ),
/// )
/// ```
334
/// {@end-tool}
335 336 337 338 339 340
///
/// See also:
///
///  * [BoxDecoration], which uses this class to describe its edge decoration.
///  * [BorderSide], which is used to describe each side of the box.
///  * [Theme], from the material layer, which can be queried to obtain appropriate colors
341
///    to use for borders in a [MaterialApp], as shown in the "divider" sample above.
Ian Hickson's avatar
Ian Hickson committed
342
class Border extends BoxBorder {
343 344 345
  /// Creates a border.
  ///
  /// All the sides of the border default to [BorderSide.none].
Ian Hickson's avatar
Ian Hickson committed
346 347
  ///
  /// The arguments must not be null.
348
  const Border({
349 350 351 352
    this.top = BorderSide.none,
    this.right = BorderSide.none,
    this.bottom = BorderSide.none,
    this.left = BorderSide.none,
Ian Hickson's avatar
Ian Hickson committed
353 354 355 356
  }) : assert(top != null),
       assert(right != null),
       assert(bottom != null),
       assert(left != null);
357

358 359 360
  /// Creates a border whose sides are all the same.
  ///
  /// The `side` argument must not be null.
361
  const Border.fromBorderSide(BorderSide side)
362 363 364 365 366 367
      : assert(side != null),
        top = side,
        right = side,
        bottom = side,
        left = side;

368 369
  /// Creates a border with symmetrical vertical and horizontal sides.
  ///
370 371
  /// The `vertical` argument applies to the [left] and [right] sides, and the
  /// `horizontal` argument applies to the [top] and [bottom] sides.
372
  ///
373
  /// All arguments default to [BorderSide.none] and must not be null.
374 375 376 377 378
  const Border.symmetric({
    BorderSide vertical = BorderSide.none,
    BorderSide horizontal = BorderSide.none,
  }) : assert(vertical != null),
       assert(horizontal != null),
379 380 381 382
       left = vertical,
       top = horizontal,
       right = vertical,
       bottom = horizontal;
383

384 385 386 387
  /// A uniform border with all sides the same color and width.
  ///
  /// The sides default to black solid borders, one logical pixel wide.
  factory Border.all({
388 389 390
    Color color = const Color(0xFF000000),
    double width = 1.0,
    BorderStyle style = BorderStyle.solid,
391
    StrokeAlign strokeAlign = StrokeAlign.inside,
392
  }) {
393
    final BorderSide side = BorderSide(color: color, width: width, style: style, strokeAlign: strokeAlign);
394
    return Border.fromBorderSide(side);
395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410
  }

  /// Creates a [Border] that represents the addition of the two given
  /// [Border]s.
  ///
  /// It is only valid to call this if [BorderSide.canMerge] returns true for
  /// the pairwise combination of each side on both [Border]s.
  ///
  /// The arguments must not be null.
  static Border merge(Border a, Border b) {
    assert(a != null);
    assert(b != null);
    assert(BorderSide.canMerge(a.top, b.top));
    assert(BorderSide.canMerge(a.right, b.right));
    assert(BorderSide.canMerge(a.bottom, b.bottom));
    assert(BorderSide.canMerge(a.left, b.left));
411
    return Border(
412 413 414 415 416 417 418
      top: BorderSide.merge(a.top, b.top),
      right: BorderSide.merge(a.right, b.right),
      bottom: BorderSide.merge(a.bottom, b.bottom),
      left: BorderSide.merge(a.left, b.left),
    );
  }

419
  @override
420 421 422 423 424
  final BorderSide top;

  /// The right side of this border.
  final BorderSide right;

425
  @override
426 427 428 429 430 431 432
  final BorderSide bottom;

  /// The left side of this border.
  final BorderSide left;

  @override
  EdgeInsetsGeometry get dimensions {
433 434 435 436 437 438 439 440 441 442
    if (isUniform) {
      switch (top.strokeAlign) {
        case StrokeAlign.inside:
          return EdgeInsets.all(top.width);
        case StrokeAlign.center:
          return EdgeInsets.all(top.width / 2);
        case StrokeAlign.outside:
          return EdgeInsets.zero;
      }
    }
443
    return EdgeInsets.fromLTRB(left.width, top.width, right.width, bottom.width);
444 445
  }

446
  @override
447
  bool get isUniform => _colorIsUniform && _widthIsUniform && _styleIsUniform && _strokeAlignIsUniform;
448 449

  bool get _colorIsUniform {
450
    final Color topColor = top.color;
451 452
    return right.color == topColor && bottom.color == topColor && left.color == topColor;
  }
453

454
  bool get _widthIsUniform {
455
    final double topWidth = top.width;
456 457
    return right.width == topWidth && bottom.width == topWidth && left.width == topWidth;
  }
458

459
  bool get _styleIsUniform {
460
    final BorderStyle topStyle = top.style;
461
    return right.style == topStyle && bottom.style == topStyle && left.style == topStyle;
462 463
  }

464 465 466 467 468 469 470
  bool get _strokeAlignIsUniform {
    final StrokeAlign topStrokeAlign = top.strokeAlign;
    return right.strokeAlign == topStrokeAlign
        && bottom.strokeAlign == topStrokeAlign
        && left.strokeAlign == topStrokeAlign;
  }

471
  @override
472
  Border? add(ShapeBorder other, { bool reversed = false }) {
473 474 475 476 477 478
    if (other is Border &&
        BorderSide.canMerge(top, other.top) &&
        BorderSide.canMerge(right, other.right) &&
        BorderSide.canMerge(bottom, other.bottom) &&
        BorderSide.canMerge(left, other.left)) {
      return Border.merge(this, other);
479 480 481 482 483 484
    }
    return null;
  }

  @override
  Border scale(double t) {
485
    return Border(
486 487 488 489 490 491 492 493
      top: top.scale(t),
      right: right.scale(t),
      bottom: bottom.scale(t),
      left: left.scale(t),
    );
  }

  @override
494
  ShapeBorder? lerpFrom(ShapeBorder? a, double t) {
495
    if (a is Border) {
496
      return Border.lerp(a, this, t);
497
    }
498 499 500 501
    return super.lerpFrom(a, t);
  }

  @override
502
  ShapeBorder? lerpTo(ShapeBorder? b, double t) {
503
    if (b is Border) {
504
      return Border.lerp(this, b, t);
505
    }
506 507 508 509 510 511 512
    return super.lerpTo(b, t);
  }

  /// Linearly interpolate between two borders.
  ///
  /// If a border is null, it is treated as having four [BorderSide.none]
  /// borders.
513
  ///
514
  /// {@macro dart.ui.shadow.lerp}
515
  static Border? lerp(Border? a, Border? b, double t) {
516
    assert(t != null);
517
    if (a == null && b == null) {
518
      return null;
519 520
    }
    if (a == null) {
521
      return b!.scale(t);
522 523
    }
    if (b == null) {
524
      return a.scale(1.0 - t);
525
    }
526
    return Border(
527 528 529
      top: BorderSide.lerp(a.top, b.top, t),
      right: BorderSide.lerp(a.right, b.right, t),
      bottom: BorderSide.lerp(a.bottom, b.bottom, t),
530
      left: BorderSide.lerp(a.left, b.left, t),
531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553
    );
  }

  /// Paints the border within the given [Rect] on the given [Canvas].
  ///
  /// Uniform borders are more efficient to paint than more complex borders.
  ///
  /// You can provide a [BoxShape] to draw the border on. If the `shape` in
  /// [BoxShape.circle], there is the requirement that the border [isUniform].
  ///
  /// If you specify a rectangular box shape ([BoxShape.rectangle]), then you
  /// may specify a [BorderRadius]. If a `borderRadius` is specified, there is
  /// the requirement that the border [isUniform].
  ///
  /// The [getInnerPath] and [getOuterPath] methods do not know about the
  /// `shape` and `borderRadius` arguments.
  ///
  /// The `textDirection` argument is not used by this paint method.
  ///
  /// See also:
  ///
  ///  * [paintBorder], which is used if the border is not uniform.
  @override
554 555 556
  void paint(
    Canvas canvas,
    Rect rect, {
557
    TextDirection? textDirection,
558
    BoxShape shape = BoxShape.rectangle,
559
    BorderRadius? borderRadius,
560 561 562 563 564 565
  }) {
    if (isUniform) {
      switch (top.style) {
        case BorderStyle.none:
          return;
        case BorderStyle.solid:
566 567 568 569 570 571 572 573 574 575 576 577
          switch (shape) {
            case BoxShape.circle:
              assert(borderRadius == null, 'A borderRadius can only be given for rectangular boxes.');
              BoxBorder._paintUniformBorderWithCircle(canvas, rect, top);
              break;
            case BoxShape.rectangle:
              if (borderRadius != null) {
                BoxBorder._paintUniformBorderWithRadius(canvas, rect, top, borderRadius);
                return;
              }
              BoxBorder._paintUniformBorderWithRectangle(canvas, rect, top);
              break;
578 579 580 581 582
          }
          return;
      }
    }

583 584 585 586 587 588 589 590
    assert(() {
      if (borderRadius != null) {
        throw FlutterError.fromParts(<DiagnosticsNode>[
          ErrorSummary('A borderRadius can only be given for a uniform Border.'),
          ErrorDescription('The following is not uniform:'),
          if (!_colorIsUniform) ErrorDescription('BorderSide.color'),
          if (!_widthIsUniform) ErrorDescription('BorderSide.width'),
          if (!_styleIsUniform) ErrorDescription('BorderSide.style'),
591
          if (!_strokeAlignIsUniform) ErrorDescription('BorderSide.strokeAlign'),
592 593 594 595 596 597 598
        ]);
      }
      return true;
    }());
    assert(() {
      if (shape != BoxShape.rectangle) {
        throw FlutterError.fromParts(<DiagnosticsNode>[
599
          ErrorSummary('A Border can only be drawn as a circle if it is uniform.'),
600 601 602 603
          ErrorDescription('The following is not uniform:'),
          if (!_colorIsUniform) ErrorDescription('BorderSide.color'),
          if (!_widthIsUniform) ErrorDescription('BorderSide.width'),
          if (!_styleIsUniform) ErrorDescription('BorderSide.style'),
604 605 606 607 608 609 610 611 612
          if (!_strokeAlignIsUniform) ErrorDescription('BorderSide.strokeAlign'),
        ]);
      }
      return true;
    }());
    assert(() {
      if (!_strokeAlignIsUniform || top.strokeAlign != StrokeAlign.inside) {
        throw FlutterError.fromParts(<DiagnosticsNode>[
          ErrorSummary('A Border can only draw strokeAlign different than StrokeAlign.inside on uniform borders.'),
613 614 615 616
        ]);
      }
      return true;
    }());
617 618 619 620 621

    paintBorder(canvas, rect, top: top, right: right, bottom: bottom, left: left);
  }

  @override
622
  bool operator ==(Object other) {
623
    if (identical(this, other)) {
624
      return true;
625 626
    }
    if (other.runtimeType != runtimeType) {
627
      return false;
628
    }
629 630 631 632 633
    return other is Border
        && other.top == top
        && other.right == right
        && other.bottom == bottom
        && other.left == left;
634 635 636
  }

  @override
637
  int get hashCode => Object.hash(top, right, bottom, left);
638 639 640

  @override
  String toString() {
641
    if (isUniform) {
642
      return '${objectRuntimeType(this, 'Border')}.all($top)';
643
    }
644 645 646 647 648 649
    final List<String> arguments = <String>[
      if (top != BorderSide.none) 'top: $top',
      if (right != BorderSide.none) 'right: $right',
      if (bottom != BorderSide.none) 'bottom: $bottom',
      if (left != BorderSide.none) 'left: $left',
    ];
650
    return '${objectRuntimeType(this, 'Border')}(${arguments.join(", ")})';
Ian Hickson's avatar
Ian Hickson committed
651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671
  }
}

/// A border of a box, comprised of four sides, the lateral sides of which
/// flip over based on the reading direction.
///
/// The lateral sides are called [start] and [end]. When painted in
/// left-to-right environments, the [start] side will be painted on the left and
/// the [end] side on the right; in right-to-left environments, it is the
/// reverse. The other two sides are [top] and [bottom].
///
/// The sides are represented by [BorderSide] objects.
///
/// If the [start] and [end] sides are the same, then it is slightly more
/// efficient to use a [Border] object rather than a [BorderDirectional] object.
///
/// See also:
///
///  * [BoxDecoration], which uses this class to describe its edge decoration.
///  * [BorderSide], which is used to describe each side of the box.
///  * [Theme], from the material layer, which can be queried to obtain appropriate colors
672
///    to use for borders in a [MaterialApp], as shown in the "divider" sample above.
Ian Hickson's avatar
Ian Hickson committed
673 674 675 676 677 678 679 680 681 682 683
class BorderDirectional extends BoxBorder {
  /// Creates a border.
  ///
  /// The [start] and [end] sides represent the horizontal sides; the start side
  /// is on the leading edge given the reading direction, and the end side is on
  /// the trailing edge. They are resolved during [paint].
  ///
  /// All the sides of the border default to [BorderSide.none].
  ///
  /// The arguments must not be null.
  const BorderDirectional({
684 685 686 687
    this.top = BorderSide.none,
    this.start = BorderSide.none,
    this.end = BorderSide.none,
    this.bottom = BorderSide.none,
Ian Hickson's avatar
Ian Hickson committed
688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706
  }) : assert(top != null),
       assert(start != null),
       assert(end != null),
       assert(bottom != null);

  /// Creates a [BorderDirectional] that represents the addition of the two
  /// given [BorderDirectional]s.
  ///
  /// It is only valid to call this if [BorderSide.canMerge] returns true for
  /// the pairwise combination of each side on both [BorderDirectional]s.
  ///
  /// The arguments must not be null.
  static BorderDirectional merge(BorderDirectional a, BorderDirectional b) {
    assert(a != null);
    assert(b != null);
    assert(BorderSide.canMerge(a.top, b.top));
    assert(BorderSide.canMerge(a.start, b.start));
    assert(BorderSide.canMerge(a.end, b.end));
    assert(BorderSide.canMerge(a.bottom, b.bottom));
707
    return BorderDirectional(
Ian Hickson's avatar
Ian Hickson committed
708 709 710 711 712 713 714
      top: BorderSide.merge(a.top, b.top),
      start: BorderSide.merge(a.start, b.start),
      end: BorderSide.merge(a.end, b.end),
      bottom: BorderSide.merge(a.bottom, b.bottom),
    );
  }

715
  @override
Ian Hickson's avatar
Ian Hickson committed
716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737
  final BorderSide top;

  /// The start side of this border.
  ///
  /// This is the side on the left in left-to-right text and on the right in
  /// right-to-left text.
  ///
  /// See also:
  ///
  ///  * [TextDirection], which is used to describe the reading direction.
  final BorderSide start;

  /// The end side of this border.
  ///
  /// This is the side on the right in left-to-right text and on the left in
  /// right-to-left text.
  ///
  /// See also:
  ///
  ///  * [TextDirection], which is used to describe the reading direction.
  final BorderSide end;

738
  @override
Ian Hickson's avatar
Ian Hickson committed
739 740 741 742
  final BorderSide bottom;

  @override
  EdgeInsetsGeometry get dimensions {
743 744 745 746 747 748 749 750 751 752
    if (isUniform) {
      switch (top.strokeAlign) {
        case StrokeAlign.inside:
          return EdgeInsetsDirectional.all(top.width);
        case StrokeAlign.center:
          return EdgeInsetsDirectional.all(top.width / 2);
        case StrokeAlign.outside:
          return EdgeInsetsDirectional.zero;
      }
    }
753
    return EdgeInsetsDirectional.fromSTEB(start.width, top.width, end.width, bottom.width);
Ian Hickson's avatar
Ian Hickson committed
754 755
  }

756
  @override
Ian Hickson's avatar
Ian Hickson committed
757 758 759 760
  bool get isUniform {
    final Color topColor = top.color;
    if (start.color != topColor ||
        end.color != topColor ||
761
        bottom.color != topColor) {
Ian Hickson's avatar
Ian Hickson committed
762
      return false;
763
    }
Ian Hickson's avatar
Ian Hickson committed
764 765 766 767

    final double topWidth = top.width;
    if (start.width != topWidth ||
        end.width != topWidth ||
768
        bottom.width != topWidth) {
Ian Hickson's avatar
Ian Hickson committed
769
      return false;
770
    }
Ian Hickson's avatar
Ian Hickson committed
771 772 773 774

    final BorderStyle topStyle = top.style;
    if (start.style != topStyle ||
        end.style != topStyle ||
775
        bottom.style != topStyle) {
Ian Hickson's avatar
Ian Hickson committed
776
      return false;
777
    }
Ian Hickson's avatar
Ian Hickson committed
778

779
    if (_strokeAlignIsUniform == false) {
780
      return false;
781
    }
782

Ian Hickson's avatar
Ian Hickson committed
783 784 785
    return true;
  }

786 787 788 789 790 791 792
  bool get _strokeAlignIsUniform {
    final StrokeAlign topStrokeAlign = top.strokeAlign;
    return start.strokeAlign == topStrokeAlign
        && bottom.strokeAlign == topStrokeAlign
        && end.strokeAlign == topStrokeAlign;
  }

Ian Hickson's avatar
Ian Hickson committed
793
  @override
794
  BoxBorder? add(ShapeBorder other, { bool reversed = false }) {
Ian Hickson's avatar
Ian Hickson committed
795 796 797 798 799 800 801 802 803 804 805 806 807
    if (other is BorderDirectional) {
      final BorderDirectional typedOther = other;
      if (BorderSide.canMerge(top, typedOther.top) &&
          BorderSide.canMerge(start, typedOther.start) &&
          BorderSide.canMerge(end, typedOther.end) &&
          BorderSide.canMerge(bottom, typedOther.bottom)) {
        return BorderDirectional.merge(this, typedOther);
      }
      return null;
    }
    if (other is Border) {
      final Border typedOther = other;
      if (!BorderSide.canMerge(typedOther.top, top) ||
808
          !BorderSide.canMerge(typedOther.bottom, bottom)) {
Ian Hickson's avatar
Ian Hickson committed
809
        return null;
810
      }
Ian Hickson's avatar
Ian Hickson committed
811 812 813
      if (start != BorderSide.none ||
          end != BorderSide.none) {
        if (typedOther.left != BorderSide.none ||
814
            typedOther.right != BorderSide.none) {
Ian Hickson's avatar
Ian Hickson committed
815
          return null;
816
        }
Ian Hickson's avatar
Ian Hickson committed
817 818
        assert(typedOther.left == BorderSide.none);
        assert(typedOther.right == BorderSide.none);
819
        return BorderDirectional(
Ian Hickson's avatar
Ian Hickson committed
820 821 822 823 824 825 826 827
          top: BorderSide.merge(typedOther.top, top),
          start: start,
          end: end,
          bottom: BorderSide.merge(typedOther.bottom, bottom),
        );
      }
      assert(start == BorderSide.none);
      assert(end == BorderSide.none);
828
      return Border(
Ian Hickson's avatar
Ian Hickson committed
829 830 831 832 833 834 835 836 837 838 839
        top: BorderSide.merge(typedOther.top, top),
        right: typedOther.right,
        bottom: BorderSide.merge(typedOther.bottom, bottom),
        left: typedOther.left,
      );
    }
    return null;
  }

  @override
  BorderDirectional scale(double t) {
840
    return BorderDirectional(
Ian Hickson's avatar
Ian Hickson committed
841 842 843 844 845 846 847 848
      top: top.scale(t),
      start: start.scale(t),
      end: end.scale(t),
      bottom: bottom.scale(t),
    );
  }

  @override
849
  ShapeBorder? lerpFrom(ShapeBorder? a, double t) {
850
    if (a is BorderDirectional) {
Ian Hickson's avatar
Ian Hickson committed
851
      return BorderDirectional.lerp(a, this, t);
852
    }
Ian Hickson's avatar
Ian Hickson committed
853 854 855 856
    return super.lerpFrom(a, t);
  }

  @override
857
  ShapeBorder? lerpTo(ShapeBorder? b, double t) {
858
    if (b is BorderDirectional) {
Ian Hickson's avatar
Ian Hickson committed
859
      return BorderDirectional.lerp(this, b, t);
860
    }
Ian Hickson's avatar
Ian Hickson committed
861 862 863 864 865 866 867
    return super.lerpTo(b, t);
  }

  /// Linearly interpolate between two borders.
  ///
  /// If a border is null, it is treated as having four [BorderSide.none]
  /// borders.
868
  ///
869
  /// {@macro dart.ui.shadow.lerp}
870
  static BorderDirectional? lerp(BorderDirectional? a, BorderDirectional? b, double t) {
871
    assert(t != null);
872
    if (a == null && b == null) {
Ian Hickson's avatar
Ian Hickson committed
873
      return null;
874 875
    }
    if (a == null) {
876
      return b!.scale(t);
877 878
    }
    if (b == null) {
Ian Hickson's avatar
Ian Hickson committed
879
      return a.scale(1.0 - t);
880
    }
881
    return BorderDirectional(
Ian Hickson's avatar
Ian Hickson committed
882 883 884
      top: BorderSide.lerp(a.top, b.top, t),
      end: BorderSide.lerp(a.end, b.end, t),
      bottom: BorderSide.lerp(a.bottom, b.bottom, t),
885
      start: BorderSide.lerp(a.start, b.start, t),
Ian Hickson's avatar
Ian Hickson committed
886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911
    );
  }

  /// Paints the border within the given [Rect] on the given [Canvas].
  ///
  /// Uniform borders are more efficient to paint than more complex borders.
  ///
  /// You can provide a [BoxShape] to draw the border on. If the `shape` in
  /// [BoxShape.circle], there is the requirement that the border [isUniform].
  ///
  /// If you specify a rectangular box shape ([BoxShape.rectangle]), then you
  /// may specify a [BorderRadius]. If a `borderRadius` is specified, there is
  /// the requirement that the border [isUniform].
  ///
  /// The [getInnerPath] and [getOuterPath] methods do not know about the
  /// `shape` and `borderRadius` arguments.
  ///
  /// The `textDirection` argument is used to determine which of [start] and
  /// [end] map to the left and right. For [TextDirection.ltr], the [start] is
  /// the left and the [end] is the right; for [TextDirection.rtl], it is the
  /// reverse.
  ///
  /// See also:
  ///
  ///  * [paintBorder], which is used if the border is not uniform.
  @override
912 913 914
  void paint(
    Canvas canvas,
    Rect rect, {
915
    TextDirection? textDirection,
916
    BoxShape shape = BoxShape.rectangle,
917
    BorderRadius? borderRadius,
Ian Hickson's avatar
Ian Hickson committed
918 919 920 921 922 923
  }) {
    if (isUniform) {
      switch (top.style) {
        case BorderStyle.none:
          return;
        case BorderStyle.solid:
924 925 926 927 928 929 930 931 932 933 934 935
          switch (shape) {
            case BoxShape.circle:
              assert(borderRadius == null, 'A borderRadius can only be given for rectangular boxes.');
              BoxBorder._paintUniformBorderWithCircle(canvas, rect, top);
              break;
            case BoxShape.rectangle:
              if (borderRadius != null) {
                BoxBorder._paintUniformBorderWithRadius(canvas, rect, top, borderRadius);
                return;
              }
              BoxBorder._paintUniformBorderWithRectangle(canvas, rect, top);
              break;
Ian Hickson's avatar
Ian Hickson committed
936 937 938 939 940 941 942
          }
          return;
      }
    }

    assert(borderRadius == null, 'A borderRadius can only be given for uniform borders.');
    assert(shape == BoxShape.rectangle, 'A border can only be drawn as a circle if it is uniform.');
943
    assert(_strokeAlignIsUniform && top.strokeAlign == StrokeAlign.inside, 'A Border can only draw strokeAlign different than StrokeAlign.inside on uniform borders.');
Ian Hickson's avatar
Ian Hickson committed
944

945
    final BorderSide left, right;
Ian Hickson's avatar
Ian Hickson committed
946
    assert(textDirection != null, 'Non-uniform BorderDirectional objects require a TextDirection when painting.');
947
    switch (textDirection!) {
Ian Hickson's avatar
Ian Hickson committed
948 949 950 951 952 953 954 955 956 957 958 959 960
      case TextDirection.rtl:
        left = end;
        right = start;
        break;
      case TextDirection.ltr:
        left = start;
        right = end;
        break;
    }
    paintBorder(canvas, rect, top: top, left: left, bottom: bottom, right: right);
  }

  @override
961
  bool operator ==(Object other) {
962
    if (identical(this, other)) {
Ian Hickson's avatar
Ian Hickson committed
963
      return true;
964 965
    }
    if (other.runtimeType != runtimeType) {
Ian Hickson's avatar
Ian Hickson committed
966
      return false;
967
    }
968 969 970 971 972
    return other is BorderDirectional
        && other.top == top
        && other.start == start
        && other.end == end
        && other.bottom == bottom;
Ian Hickson's avatar
Ian Hickson committed
973 974 975
  }

  @override
976
  int get hashCode => Object.hash(top, start, end, bottom);
Ian Hickson's avatar
Ian Hickson committed
977 978 979

  @override
  String toString() {
980 981 982 983 984 985
    final List<String> arguments = <String>[
      if (top != BorderSide.none) 'top: $top',
      if (start != BorderSide.none) 'start: $start',
      if (end != BorderSide.none) 'end: $end',
      if (bottom != BorderSide.none) 'bottom: $bottom',
    ];
986
    return '${objectRuntimeType(this, 'BorderDirectional')}(${arguments.join(", ")})';
987 988
  }
}