table.dart 46.7 KB
Newer Older
Hixie's avatar
Hixie committed
1 2 3 4 5 6 7
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:collection';
import 'dart:math' as math;

8 9
import 'package:flutter/foundation.dart';

Hixie's avatar
Hixie committed
10 11 12 13 14
import 'box.dart';
import 'object.dart';

/// Parent data used by [RenderTable] for its children.
class TableCellParentData extends BoxParentData {
15
  /// Where this cell should be placed vertically.
Hixie's avatar
Hixie committed
16 17
  TableCellVerticalAlignment verticalAlignment;

Hixie's avatar
Hixie committed
18 19 20 21 22 23
  /// The column that the child was in the last time it was laid out.
  int x;

  /// The row that the child was in the last time it was laid out.
  int y;

Hixie's avatar
Hixie committed
24
  @override
25
  String toString() => '${super.toString()}; ${verticalAlignment == null ? "default vertical alignment" : "$verticalAlignment"}';
Hixie's avatar
Hixie committed
26 27 28
}

/// Base class to describe how wide a column in a [RenderTable] should be.
29 30 31 32 33 34 35 36
///
/// To size a column to a specific number of pixels, use a [FixedColumnWidth].
/// This is the cheapest way to size a column.
///
/// Other algorithms that are relatively cheap include [FlexColumnWidth], which
/// distributes the space equally among the flexible columns,
/// [FractionColumnWidth], which sizes a column based on the size of the
/// table's container.
37
@immutable
Hixie's avatar
Hixie committed
38
abstract class TableColumnWidth {
39 40
  /// Abstract const constructor. This constructor enables subclasses to provide
  /// const constructors so that they can be used in const expressions.
Hixie's avatar
Hixie committed
41 42
  const TableColumnWidth();

43 44 45 46 47 48 49 50
  /// The smallest width that the column can have.
  ///
  /// The `cells` argument is an iterable that provides all the cells
  /// in the table for this column. Walking the cells is by definition
  /// O(N), so algorithms that do that should be considered expensive.
  ///
  /// The `containerWidth` argument is the `maxWidth` of the incoming
  /// constraints for the table, and might be infinite.
Hixie's avatar
Hixie committed
51 52
  double minIntrinsicWidth(Iterable<RenderBox> cells, double containerWidth);

53 54 55 56 57 58 59 60 61 62 63 64
  /// The ideal width that the column should have. This must be equal
  /// to or greater than the [minIntrinsicWidth]. The column might be
  /// bigger than this width, e.g. if the column is flexible or if the
  /// table's width ends up being forced to be bigger than the sum of
  /// all the maxIntrinsicWidth values.
  ///
  /// The `cells` argument is an iterable that provides all the cells
  /// in the table for this column. Walking the cells is by definition
  /// O(N), so algorithms that do that should be considered expensive.
  ///
  /// The `containerWidth` argument is the `maxWidth` of the incoming
  /// constraints for the table, and might be infinite.
Hixie's avatar
Hixie committed
65 66
  double maxIntrinsicWidth(Iterable<RenderBox> cells, double containerWidth);

67 68 69 70 71 72 73 74
  /// The flex factor to apply to the cell if there is any room left
  /// over when laying out the table. The remaining space is
  /// distributed to any columns with flex in proportion to their flex
  /// value (higher values get more space).
  ///
  /// The `cells` argument is an iterable that provides all the cells
  /// in the table for this column. Walking the cells is by definition
  /// O(N), so algorithms that do that should be considered expensive.
Hixie's avatar
Hixie committed
75 76 77 78 79 80 81 82 83 84
  double flex(Iterable<RenderBox> cells) => null;

  @override
  String toString() => '$runtimeType';
}

/// Sizes the column according to the intrinsic dimensions of all the
/// cells in that column.
///
/// This is a very expensive way to size a column.
85 86 87 88
///
/// A flex value can be provided. If specified (and non-null), the
/// column will participate in the distribution of remaining space
/// once all the non-flexible columns have been sized.
89
class IntrinsicColumnWidth extends TableColumnWidth {
90 91 92
  /// Creates a column width based on intrinsic sizing.
  ///
  /// This sizing algorithm is very expensive.
93
  const IntrinsicColumnWidth({ double flex }) : _flex = flex;
Hixie's avatar
Hixie committed
94 95 96 97 98

  @override
  double minIntrinsicWidth(Iterable<RenderBox> cells, double containerWidth) {
    double result = 0.0;
    for (RenderBox cell in cells)
99
      result = math.max(result, cell.getMinIntrinsicWidth(double.INFINITY));
Hixie's avatar
Hixie committed
100 101 102 103 104 105 106
    return result;
  }

  @override
  double maxIntrinsicWidth(Iterable<RenderBox> cells, double containerWidth) {
    double result = 0.0;
    for (RenderBox cell in cells)
107
      result = math.max(result, cell.getMaxIntrinsicWidth(double.INFINITY));
Hixie's avatar
Hixie committed
108 109
    return result;
  }
110 111 112 113 114

  final double _flex;

  @override
  double flex(Iterable<RenderBox> cells) => _flex;
Hixie's avatar
Hixie committed
115 116 117 118 119 120
}

/// Sizes the column to a specific number of pixels.
///
/// This is the cheapest way to size a column.
class FixedColumnWidth extends TableColumnWidth {
121 122 123
  /// Creates a column width based on a fixed number of logical pixels.
  ///
  /// The [value] argument must not be null.
124
  const FixedColumnWidth(this.value) : assert(value != null);
125 126

  /// The width the column should occupy in logical pixels.
Hixie's avatar
Hixie committed
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
  final double value;

  @override
  double minIntrinsicWidth(Iterable<RenderBox> cells, double containerWidth) {
    return value;
  }

  @override
  double maxIntrinsicWidth(Iterable<RenderBox> cells, double containerWidth) {
    return value;
  }

  @override
  String toString() => '$runtimeType($value)';
}

/// Sizes the column to a fraction of the table's constraints' maxWidth.
///
/// This is a cheap way to size a column.
class FractionColumnWidth extends TableColumnWidth {
147 148 149 150
  /// Creates a column width based on a fraction of the table's constraints'
  /// maxWidth.
  ///
  /// The [value] argument must not be null.
151
  const FractionColumnWidth(this.value) : assert(value != null);
152 153 154

  /// The fraction of the table's constraints' maxWidth that this column should
  /// occupy.
Hixie's avatar
Hixie committed
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
  final double value;

  @override
  double minIntrinsicWidth(Iterable<RenderBox> cells, double containerWidth) {
    if (!containerWidth.isFinite)
      return 0.0;
    return value * containerWidth;
  }

  @override
  double maxIntrinsicWidth(Iterable<RenderBox> cells, double containerWidth) {
    if (!containerWidth.isFinite)
      return 0.0;
    return value * containerWidth;
  }

  @override
  String toString() => '$runtimeType($value)';
}

/// Sizes the column by taking a part of the remaining space once all
/// the other columns have been laid out.
///
178
/// For example, if two columns have a [FlexColumnWidth], then half the
Hixie's avatar
Hixie committed
179 180 181 182
/// space will go to one and half the space will go to the other.
///
/// This is a cheap way to size a column.
class FlexColumnWidth extends TableColumnWidth {
183 184 185 186
  /// Creates a column width based on a fraction of the remaining space once all
  /// the other columns have been laid out.
  ///
  /// The [value] argument must not be null.
187
  const FlexColumnWidth([this.value = 1.0]) : assert(value != null);
188 189 190

  /// The reaction of the of the remaining space once all the other columns have
  /// been laid out that this column should occupy.
Hixie's avatar
Hixie committed
191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
  final double value;

  @override
  double minIntrinsicWidth(Iterable<RenderBox> cells, double containerWidth) {
    return 0.0;
  }

  @override
  double maxIntrinsicWidth(Iterable<RenderBox> cells, double containerWidth) {
    return 0.0;
  }

  @override
  double flex(Iterable<RenderBox> cells) {
    return value;
  }

  @override
  String toString() => '$runtimeType($value)';
}

/// Sizes the column such that it is the size that is the maximum of
/// two column width specifications.
///
/// For example, to have a column be 10% of the container width or
/// 100px, whichever is bigger, you could use:
///
///     const MaxColumnWidth(const FixedColumnWidth(100.0), FractionColumnWidth(0.1))
///
/// Both specifications are evaluated, so if either specification is
/// expensive, so is this.
class MaxColumnWidth extends TableColumnWidth {
223
  /// Creates a column width that is the maximum of two other column widths.
Hixie's avatar
Hixie committed
224
  const MaxColumnWidth(this.a, this.b);
225 226

  /// A lower bound for the width of this column.
Hixie's avatar
Hixie committed
227
  final TableColumnWidth a;
228 229

  /// Another lower bound for the width of this column.
Hixie's avatar
Hixie committed
230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249
  final TableColumnWidth b;

  @override
  double minIntrinsicWidth(Iterable<RenderBox> cells, double containerWidth) {
    return math.max(
      a.minIntrinsicWidth(cells, containerWidth),
      b.minIntrinsicWidth(cells, containerWidth)
    );
  }

  @override
  double maxIntrinsicWidth(Iterable<RenderBox> cells, double containerWidth) {
    return math.max(
      a.maxIntrinsicWidth(cells, containerWidth),
      b.maxIntrinsicWidth(cells, containerWidth)
    );
  }

  @override
  double flex(Iterable<RenderBox> cells) {
250
    final double aFlex = a.flex(cells);
Hixie's avatar
Hixie committed
251 252
    if (aFlex == null)
      return b.flex(cells);
253 254 255 256
    final double bFlex = b.flex(cells);
    if (bFlex == null)
      return null;
    return math.max(aFlex, bFlex);
Hixie's avatar
Hixie committed
257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273
  }

  @override
  String toString() => '$runtimeType($a, $b)';
}

/// Sizes the column such that it is the size that is the minimum of
/// two column width specifications.
///
/// For example, to have a column be 10% of the container width but
/// never bigger than 100px, you could use:
///
///     const MinColumnWidth(const FixedColumnWidth(100.0), FractionColumnWidth(0.1))
///
/// Both specifications are evaluated, so if either specification is
/// expensive, so is this.
class MinColumnWidth extends TableColumnWidth {
274 275 276 277
  /// Creates a column width that is the minimum of two other column widths.
  const MinColumnWidth(this.a, this.b);

  /// An upper bound for the width of this column.
Hixie's avatar
Hixie committed
278
  final TableColumnWidth a;
279 280

  /// Another upper bound for the width of this column.
Hixie's avatar
Hixie committed
281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300
  final TableColumnWidth b;

  @override
  double minIntrinsicWidth(Iterable<RenderBox> cells, double containerWidth) {
    return math.min(
      a.minIntrinsicWidth(cells, containerWidth),
      b.minIntrinsicWidth(cells, containerWidth)
    );
  }

  @override
  double maxIntrinsicWidth(Iterable<RenderBox> cells, double containerWidth) {
    return math.min(
      a.maxIntrinsicWidth(cells, containerWidth),
      b.maxIntrinsicWidth(cells, containerWidth)
    );
  }

  @override
  double flex(Iterable<RenderBox> cells) {
301
    final double aFlex = a.flex(cells);
Hixie's avatar
Hixie committed
302 303
    if (aFlex == null)
      return b.flex(cells);
304
    final double bFlex = b.flex(cells);
305 306 307
    if (bFlex == null)
      return null;
    return math.min(aFlex, bFlex);
Hixie's avatar
Hixie committed
308 309 310 311 312 313 314 315 316 317 318
  }

  @override
  String toString() => '$runtimeType($a, $b)';
}

/// Border specification for [RenderTable].
///
/// This is like [Border], with the addition of two sides: the inner
/// horizontal borders and the inner vertical borders.
class TableBorder extends Border {
319 320 321
  /// Creates a border for a table.
  ///
  /// All the sides of the border default to [BorderSide.none].
Hixie's avatar
Hixie committed
322 323 324 325 326 327 328 329 330 331 332 333 334 335
  const TableBorder({
    BorderSide top: BorderSide.none,
    BorderSide right: BorderSide.none,
    BorderSide bottom: BorderSide.none,
    BorderSide left: BorderSide.none,
    this.horizontalInside: BorderSide.none,
    this.verticalInside: BorderSide.none
  }) : super(
    top: top,
    right: right,
    bottom: bottom,
    left: left
  );

336
  /// A uniform border with all sides the same color and width.
Hixie's avatar
Hixie committed
337 338 339 340 341 342 343 344
  factory TableBorder.all({
    Color color: const Color(0xFF000000),
    double width: 1.0
  }) {
    final BorderSide side = new BorderSide(color: color, width: width);
    return new TableBorder(top: side, right: side, bottom: side, left: side, horizontalInside: side, verticalInside: side);
  }

345 346
  /// Creates a border for a table where all the interior sides use the same
  /// styling and all the exterior sides use the same styling.
Hixie's avatar
Hixie committed
347 348 349 350 351 352 353 354 355 356 357 358 359 360
  factory TableBorder.symmetric({
    BorderSide inside: BorderSide.none,
    BorderSide outside: BorderSide.none
  }) {
    return new TableBorder(
      top: outside,
      right: outside,
      bottom: outside,
      left: outside,
      horizontalInside: inside,
      verticalInside: inside
    );
  }

361
  /// The horizontal interior sides of this border.
Hixie's avatar
Hixie committed
362 363
  final BorderSide horizontalInside;

364
  /// The vertical interior sides of this border.
Hixie's avatar
Hixie committed
365 366
  final BorderSide verticalInside;

367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391
  @override
  bool get isUniform {
    assert(horizontalInside != null);
    assert(verticalInside != null);
    if (!super.isUniform)
      return false;

    final Color topColor = top.color;
    if (horizontalInside.color != topColor ||
        verticalInside.color != topColor)
      return false;

    final double topWidth = top.width;
    if (horizontalInside.width != topWidth ||
        verticalInside.width != topWidth)
      return false;

    final BorderStyle topStyle = top.style;
    if (horizontalInside.style != topStyle ||
        verticalInside.style != topStyle)
      return false;

    return true;
  }

Hixie's avatar
Hixie committed
392 393 394 395 396 397 398 399 400 401 402 403
  @override
  TableBorder scale(double t) {
    return new TableBorder(
      top: top.copyWith(width: t * top.width),
      right: right.copyWith(width: t * right.width),
      bottom: bottom.copyWith(width: t * bottom.width),
      left: left.copyWith(width: t * left.width),
      horizontalInside: horizontalInside.copyWith(width: t * horizontalInside.width),
      verticalInside: verticalInside.copyWith(width: t * verticalInside.width)
    );
  }

404
  /// Linearly interpolate between two table borders.
Hixie's avatar
Hixie committed
405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453
  static TableBorder lerp(TableBorder a, TableBorder b, double t) {
    if (a == null && b == null)
      return null;
    if (a == null)
      return b.scale(t);
    if (b == null)
      return a.scale(1.0 - t);
    return new TableBorder(
      top: BorderSide.lerp(a.top, b.top, t),
      right: BorderSide.lerp(a.right, b.right, t),
      bottom: BorderSide.lerp(a.bottom, b.bottom, t),
      left: BorderSide.lerp(a.left, b.left, t),
      horizontalInside: BorderSide.lerp(a.horizontalInside, b.horizontalInside, t),
      verticalInside: BorderSide.lerp(a.verticalInside, b.verticalInside, t)
    );
  }

  @override
  bool operator ==(dynamic other) {
    if (super != other)
      return false;
    final TableBorder typedOther = other;
    return horizontalInside == typedOther.horizontalInside &&
           verticalInside == typedOther.verticalInside;
  }

  @override
  int get hashCode => hashValues(super.hashCode, horizontalInside, verticalInside);

  @override
  String toString() => 'TableBorder($top, $right, $bottom, $left, $horizontalInside, $verticalInside)';
}

/// Vertical alignment options for cells in [RenderTable] objects.
///
/// This is specified using [TableCellParentData] objects on the
/// [RenderObject.parentData] of the children of the [RenderTable].
enum TableCellVerticalAlignment {
  /// Cells with this alignment are placed with their top at the top of the row.
  top,

  /// Cells with this alignment are vertically centered in the row.
  middle,

  /// Cells with this alignment are placed with their bottom at the bottom of the row.
  bottom,

  /// Cells with this alignment are aligned such that they all share the same
  /// baseline. Cells with no baseline are top-aligned instead. The baseline
Ian Hickson's avatar
Ian Hickson committed
454 455
  /// used is specified by [RenderTable.textBaseline]. It is not valid to use
  /// the baseline value if [RenderTable.textBaseline] is not specified.
456 457 458
  ///
  /// This vertial alignment is relatively expensive because it causes the table
  /// to compute the baseline for each cell in the row.
Hixie's avatar
Hixie committed
459 460 461 462 463 464 465 466 467
  baseline,

  /// Cells with this alignment are sized to be as tall as the row, then made to fit the row.
  /// If all the cells have this alignment, then the row will have zero height.
  fill
}

/// A table where the columns and rows are sized to fit the contents of the cells.
class RenderTable extends RenderBox {
468 469 470 471 472 473 474 475 476 477 478
  /// Creates a table render object.
  ///
  ///  * `columns` must either be null or non-negative. If `columns` is null,
  ///    the number of columns will be inferred from length of the first sublist
  ///    of `children`.
  ///  * `rows` must either be null or non-negative. If `rows` is null, the
  ///    number of rows will be inferred from the `children`. If `rows` is not
  ///    null, then `children` must be null.
  ///  * `children` must either be null or contain lists of all the same length.
  ///    if `children` is not null, then `rows` must be null.
  ///  * [defaultColumnWidth] must not be null.
479
  ///  * [configuration] must not be null (but has a default value).
Hixie's avatar
Hixie committed
480 481 482 483 484 485
  RenderTable({
    int columns,
    int rows,
    Map<int, TableColumnWidth> columnWidths,
    TableColumnWidth defaultColumnWidth: const FlexColumnWidth(1.0),
    TableBorder border,
486
    List<Decoration> rowDecorations,
487
    ImageConfiguration configuration: ImageConfiguration.empty,
488
    Decoration defaultRowDecoration,
Hixie's avatar
Hixie committed
489 490 491
    TableCellVerticalAlignment defaultVerticalAlignment: TableCellVerticalAlignment.top,
    TextBaseline textBaseline,
    List<List<RenderBox>> children
492 493 494 495 496
  }) : assert(columns == null || columns >= 0),
       assert(rows == null || rows >= 0),
       assert(rows == null || children == null),
       assert(defaultColumnWidth != null),
       assert(configuration != null) {
497
    _columns = columns ?? (children != null && children.isNotEmpty ? children.first.length : 0);
Hixie's avatar
Hixie committed
498
    _rows = rows ?? 0;
499
    _children = <RenderBox>[]..length = _columns * _rows;
Hixie's avatar
Hixie committed
500 501 502
    _columnWidths = columnWidths ?? new HashMap<int, TableColumnWidth>();
    _defaultColumnWidth = defaultColumnWidth;
    _border = border;
503 504
    this.rowDecorations = rowDecorations; // must use setter to initialize box painters array
    _configuration = configuration;
Hixie's avatar
Hixie committed
505 506 507 508 509 510 511 512 513 514 515 516
    _defaultVerticalAlignment = defaultVerticalAlignment;
    _textBaseline = textBaseline;
    if (children != null) {
      for (List<RenderBox> row in children)
        addRow(row);
    }
  }

  // Children are stored in row-major order.
  // _children.length must be rows * columns
  List<RenderBox> _children = const <RenderBox>[];

517 518 519 520 521 522 523
  /// The number of vertical alignment lines in this table.
  ///
  /// Changing the number of columns will remove any children that no longer fit
  /// in the table.
  ///
  /// Changing the number of columns is an expensive operation because the table
  /// needs to rearranage its internal representation.
Hixie's avatar
Hixie committed
524 525
  int get columns => _columns;
  int _columns;
526
  set columns(int value) {
Hixie's avatar
Hixie committed
527 528 529 530
    assert(value != null);
    assert(value >= 0);
    if (value == columns)
      return;
531 532
    final int oldColumns = columns;
    final List<RenderBox> oldChildren = _children;
Hixie's avatar
Hixie committed
533
    _columns = value;
534
    _children = <RenderBox>[]..length = columns * rows;
535
    final int columnsToCopy = math.min(columns, oldColumns);
Hixie's avatar
Hixie committed
536 537 538 539
    for (int y = 0; y < rows; y += 1) {
      for (int x = 0; x < columnsToCopy; x += 1)
        _children[x + y * columns] = oldChildren[x + y * oldColumns];
    }
Hixie's avatar
Hixie committed
540 541 542
    if (oldColumns > columns) {
      for (int y = 0; y < rows; y += 1) {
        for (int x = columns; x < oldColumns; x += 1) {
543
          final int xy = x + y * oldColumns;
Hixie's avatar
Hixie committed
544 545 546 547 548
          if (oldChildren[xy] != null)
            dropChild(oldChildren[xy]);
        }
      }
    }
Hixie's avatar
Hixie committed
549 550 551
    markNeedsLayout();
  }

552 553 554 555
  /// The number of horizontal alignment lines in this table.
  ///
  /// Changing the number of rows will remove any children that no longer fit
  /// in the table.
Hixie's avatar
Hixie committed
556 557
  int get rows => _rows;
  int _rows;
558
  set rows(int value) {
Hixie's avatar
Hixie committed
559 560 561 562
    assert(value != null);
    assert(value >= 0);
    if (value == rows)
      return;
Hixie's avatar
Hixie committed
563 564 565 566 567 568
    if (_rows > value) {
      for (int xy = columns * value; xy < _children.length; xy += 1) {
        if (_children[xy] != null)
          dropChild(_children[xy]);
      }
    }
Hixie's avatar
Hixie committed
569 570 571 572 573
    _rows = value;
    _children.length = columns * rows;
    markNeedsLayout();
  }

574 575 576 577 578 579 580 581 582
  /// How the horizontal extents of the columns of this table should be determined.
  ///
  /// If the [Map] has a null entry for a given column, the table uses the
  /// [defaultColumnWidth] instead.
  ///
  /// The layout performance of the table depends critically on which column
  /// sizing algorithms are used here. In particular, [IntrinsicColumnWidth] is
  /// quite expensive because it needs to measure each cell in the column to
  /// determine the intrinsic size of the column.
Hixie's avatar
Hixie committed
583
  Map<int, TableColumnWidth> get columnWidths => new Map<int, TableColumnWidth>.unmodifiable(_columnWidths);
584
  Map<int, TableColumnWidth> _columnWidths;
585
  set columnWidths(Map<int, TableColumnWidth> value) {
Hixie's avatar
Hixie committed
586
    value ??= new HashMap<int, TableColumnWidth>();
Hixie's avatar
Hixie committed
587 588 589 590 591 592
    if (_columnWidths == value)
      return;
    _columnWidths = value;
    markNeedsLayout();
  }

593
  /// Determines how the width of column with the given index is determined.
Hixie's avatar
Hixie committed
594 595 596 597 598 599 600
  void setColumnWidth(int column, TableColumnWidth value) {
    if (_columnWidths[column] == value)
      return;
    _columnWidths[column] = value;
    markNeedsLayout();
  }

601 602 603 604
  /// How to determine with widths of columns that don't have an explicit sizing algorithm.
  ///
  /// Specifically, the [defaultColumnWidth] is used for column `i` if
  /// `columnWidths[i]` is null.
Hixie's avatar
Hixie committed
605 606
  TableColumnWidth get defaultColumnWidth => _defaultColumnWidth;
  TableColumnWidth _defaultColumnWidth;
607
  set defaultColumnWidth(TableColumnWidth value) {
Hixie's avatar
Hixie committed
608 609 610 611 612 613 614
    assert(value != null);
    if (defaultColumnWidth == value)
      return;
    _defaultColumnWidth = value;
    markNeedsLayout();
  }

615
  /// The style to use when painting the boundary and interior divisions of the table.
Hixie's avatar
Hixie committed
616 617
  TableBorder get border => _border;
  TableBorder _border;
618
  set border(TableBorder value) {
Hixie's avatar
Hixie committed
619 620 621 622 623
    if (border == value)
      return;
    _border = value;
    markNeedsPaint();
  }
624

625 626 627 628 629
  /// The decorations to use for each row of the table.
  ///
  /// Row decorations fill the horizontal and vertical extent of each row in
  /// the table, unlike decorations for individual cells, which might not fill
  /// either.
630 631 632
  List<Decoration> get rowDecorations => new List<Decoration>.unmodifiable(_rowDecorations ?? const <Decoration>[]);
  List<Decoration> _rowDecorations;
  List<BoxPainter> _rowDecorationPainters;
633
  set rowDecorations(List<Decoration> value) {
634 635 636
    if (_rowDecorations == value)
      return;
    _rowDecorations = value;
637 638 639
    if (_rowDecorationPainters != null) {
      for (BoxPainter painter in _rowDecorationPainters)
        painter?.dispose();
640
    }
641
    _rowDecorationPainters = _rowDecorations != null ? new List<BoxPainter>(_rowDecorations.length) : null;
642 643
  }

644 645 646 647 648
  /// The settings to pass to the [rowDecorations] when painting, so that they
  /// can resolve images appropriately. See [ImageProvider.resolve] and
  /// [BoxPainter.paint].
  ImageConfiguration get configuration => _configuration;
  ImageConfiguration _configuration;
649
  set configuration(ImageConfiguration value) {
650 651 652 653 654
    assert(value != null);
    if (value == _configuration)
      return;
    _configuration = value;
    markNeedsPaint();
655
  }
Hixie's avatar
Hixie committed
656

657
  /// How cells that do not explicitly specify a vertical alignment are aligned vertically.
Hixie's avatar
Hixie committed
658 659
  TableCellVerticalAlignment get defaultVerticalAlignment => _defaultVerticalAlignment;
  TableCellVerticalAlignment _defaultVerticalAlignment;
660
  set defaultVerticalAlignment(TableCellVerticalAlignment value) {
Hixie's avatar
Hixie committed
661 662 663 664 665 666
    if (_defaultVerticalAlignment == value)
      return;
    _defaultVerticalAlignment = value;
    markNeedsLayout();
  }

667
  /// The text baseline to use when aligning rows using [TableCellVerticalAlignment.baseline].
Hixie's avatar
Hixie committed
668 669
  TextBaseline get textBaseline => _textBaseline;
  TextBaseline _textBaseline;
670
  set textBaseline(TextBaseline value) {
Hixie's avatar
Hixie committed
671 672 673 674 675 676 677 678 679 680 681 682
    if (_textBaseline == value)
      return;
    _textBaseline = value;
    markNeedsLayout();
  }

  @override
  void setupParentData(RenderObject child) {
    if (child.parentData is! TableCellParentData)
      child.parentData = new TableCellParentData();
  }

683 684 685 686 687 688 689 690
  /// Replaces the children of this table with the given cells.
  ///
  /// The cells are divided into the specified number of columns before
  /// replacing the existing children.
  ///
  /// If the new cells contain any existing children of the table, those
  /// children are simply moved to their new location in the table rather than
  /// removed from the table and re-added.
Hixie's avatar
Hixie committed
691 692 693 694
  void setFlatChildren(int columns, List<RenderBox> cells) {
    if (cells == _children && columns == _columns)
      return;
    assert(columns >= 0);
Hixie's avatar
Hixie committed
695
    // consider the case of a newly empty table
696 697
    if (columns == 0 || cells.isEmpty) {
      assert(cells == null || cells.isEmpty);
Hixie's avatar
Hixie committed
698
      _columns = columns;
699
      if (_children.isEmpty) {
Hixie's avatar
Hixie committed
700
        assert(_rows == 0);
Hixie's avatar
Hixie committed
701
        return;
Hixie's avatar
Hixie committed
702
      }
Hixie's avatar
Hixie committed
703
      for (RenderBox oldChild in _children) {
Hixie's avatar
Hixie committed
704 705 706
        if (oldChild != null)
          dropChild(oldChild);
      }
Hixie's avatar
Hixie committed
707 708 709 710 711 712 713
      _rows = 0;
      _children.clear();
      markNeedsLayout();
      return;
    }
    assert(cells != null);
    assert(cells.length % columns == 0);
714 715 716 717
    // fill a set with the cells that are moving (it's important not
    // to dropChild a child that's remaining with us, because that
    // would clear their parentData field)
    final Set<RenderBox> lostChildren = new HashSet<RenderBox>();
Hixie's avatar
Hixie committed
718 719
    for (int y = 0; y < _rows; y += 1) {
      for (int x = 0; x < _columns; x += 1) {
720 721
        final int xyOld = x + y * _columns;
        final int xyNew = x + y * columns;
Hixie's avatar
Hixie committed
722
        if (_children[xyOld] != null && (x >= columns || xyNew >= cells.length || _children[xyOld] != cells[xyNew]))
723
          lostChildren.add(_children[xyOld]);
Hixie's avatar
Hixie committed
724
      }
Hixie's avatar
Hixie committed
725
    }
726
    // adopt cells that are arriving, and cross cells that are just moving off our list of lostChildren
Hixie's avatar
Hixie committed
727 728 729
    int y = 0;
    while (y * columns < cells.length) {
      for (int x = 0; x < columns; x += 1) {
730 731
        final int xyNew = x + y * columns;
        final int xyOld = x + y * _columns;
732 733 734 735
        if (cells[xyNew] != null && (x >= _columns || y >= _rows || _children[xyOld] != cells[xyNew])) {
          if (!lostChildren.remove(cells[xyNew]))
            adoptChild(cells[xyNew]);
        }
Hixie's avatar
Hixie committed
736 737 738
      }
      y += 1;
    }
739 740 741
    // drop all the lost children
    for (RenderBox oldChild in lostChildren)
      dropChild(oldChild);
Hixie's avatar
Hixie committed
742 743 744 745 746
    // update our internal values
    _columns = columns;
    _rows = cells.length ~/ columns;
    _children = cells.toList();
    assert(_children.length == rows * columns);
Hixie's avatar
Hixie committed
747 748 749
    markNeedsLayout();
  }

750
  /// Replaces the children of this table with the given cells.
Hixie's avatar
Hixie committed
751
  void setChildren(List<List<RenderBox>> cells) {
Hixie's avatar
Hixie committed
752
    // TODO(ianh): Make this smarter, like setFlatChildren
Hixie's avatar
Hixie committed
753 754 755 756
    if (cells == null) {
      setFlatChildren(0, null);
      return;
    }
Hixie's avatar
Hixie committed
757
    for (RenderBox oldChild in _children) {
Hixie's avatar
Hixie committed
758 759 760
      if (oldChild != null)
        dropChild(oldChild);
    }
Hixie's avatar
Hixie committed
761
    _children.clear();
762
    _columns = cells.isNotEmpty ? cells.first.length : 0;
Hixie's avatar
Hixie committed
763 764 765
    _rows = 0;
    for (List<RenderBox> row in cells)
      addRow(row);
Hixie's avatar
Hixie committed
766
    assert(_children.length == rows * columns);
Hixie's avatar
Hixie committed
767 768
  }

769 770 771
  /// Adds a row to the end of the table.
  ///
  /// The newly added children must not already have parents.
Hixie's avatar
Hixie committed
772 773
  void addRow(List<RenderBox> cells) {
    assert(cells.length == columns);
Hixie's avatar
Hixie committed
774
    assert(_children.length == rows * columns);
Hixie's avatar
Hixie committed
775 776 777 778 779 780 781 782 783
    _rows += 1;
    _children.addAll(cells);
    for (RenderBox cell in cells) {
      if (cell != null)
        adoptChild(cell);
    }
    markNeedsLayout();
  }

784 785 786 787 788
  /// Replaces the child at the given position with the given child.
  ///
  /// If the given child is already located at the given position, this function
  /// does not modify the table. Otherwise, the given child must not already
  /// have a parent.
Hixie's avatar
Hixie committed
789 790 791 792
  void setChild(int x, int y, RenderBox value) {
    assert(x != null);
    assert(y != null);
    assert(x >= 0 && x < columns && y >= 0 && y < rows);
Hixie's avatar
Hixie committed
793
    assert(_children.length == rows * columns);
Hixie's avatar
Hixie committed
794
    final int xy = x + y * columns;
795
    final RenderBox oldChild = _children[xy];
Hixie's avatar
Hixie committed
796 797
    if (oldChild == value)
      return;
Hixie's avatar
Hixie committed
798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813
    if (oldChild != null)
      dropChild(oldChild);
    _children[xy] = value;
    if (value != null)
      adoptChild(value);
  }

  @override
  void attach(PipelineOwner owner) {
    super.attach(owner);
    for (RenderBox child in _children)
      child?.attach(owner);
  }

  @override
  void detach() {
814
    super.detach();
815 816 817 818 819
    if (_rowDecorationPainters != null) {
      for (BoxPainter painter in _rowDecorationPainters)
        painter?.dispose();
      _rowDecorationPainters = null;
    }
Hixie's avatar
Hixie committed
820 821 822 823 824 825
    for (RenderBox child in _children)
      child?.detach();
  }

  @override
  void visitChildren(RenderObjectVisitor visitor) {
Hixie's avatar
Hixie committed
826
    assert(_children.length == rows * columns);
Hixie's avatar
Hixie committed
827 828 829 830 831 832 833
    for (RenderBox child in _children) {
      if (child != null)
        visitor(child);
    }
  }

  @override
834
  double computeMinIntrinsicWidth(double height) {
Hixie's avatar
Hixie committed
835
    assert(_children.length == rows * columns);
Hixie's avatar
Hixie committed
836 837
    double totalMinWidth = 0.0;
    for (int x = 0; x < columns; x += 1) {
838 839
      final TableColumnWidth columnWidth = _columnWidths[x] ?? defaultColumnWidth;
      final Iterable<RenderBox> columnCells = column(x);
840
      totalMinWidth += columnWidth.minIntrinsicWidth(columnCells, double.INFINITY);
Hixie's avatar
Hixie committed
841
    }
842
    return totalMinWidth;
Hixie's avatar
Hixie committed
843 844 845
  }

  @override
846
  double computeMaxIntrinsicWidth(double height) {
Hixie's avatar
Hixie committed
847
    assert(_children.length == rows * columns);
Hixie's avatar
Hixie committed
848 849
    double totalMaxWidth = 0.0;
    for (int x = 0; x < columns; x += 1) {
850 851
      final TableColumnWidth columnWidth = _columnWidths[x] ?? defaultColumnWidth;
      final Iterable<RenderBox> columnCells = column(x);
852
      totalMaxWidth += columnWidth.maxIntrinsicWidth(columnCells, double.INFINITY);
Hixie's avatar
Hixie committed
853
    }
854
    return totalMaxWidth;
Hixie's avatar
Hixie committed
855 856 857
  }

  @override
858
  double computeMinIntrinsicHeight(double width) {
Hixie's avatar
Hixie committed
859 860
    // winner of the 2016 world's most expensive intrinsic dimension function award
    // honorable mention, most likely to improve if taught about memoization award
Hixie's avatar
Hixie committed
861
    assert(_children.length == rows * columns);
862
    final List<double> widths = _computeColumnWidths(new BoxConstraints.tightForFinite(width: width));
Hixie's avatar
Hixie committed
863 864 865 866 867
    double rowTop = 0.0;
    for (int y = 0; y < rows; y += 1) {
      double rowHeight = 0.0;
      for (int x = 0; x < columns; x += 1) {
        final int xy = x + y * columns;
868
        final RenderBox child = _children[xy];
Hixie's avatar
Hixie committed
869
        if (child != null)
870
          rowHeight = math.max(rowHeight, child.getMaxIntrinsicHeight(widths[x]));
Hixie's avatar
Hixie committed
871 872 873
      }
      rowTop += rowHeight;
    }
874
    return rowTop;
Hixie's avatar
Hixie committed
875 876 877
  }

  @override
878 879
  double computeMaxIntrinsicHeight(double width) {
    return computeMinIntrinsicHeight(width);
Hixie's avatar
Hixie committed
880 881 882 883 884 885
  }

  double _baselineDistance;
  @override
  double computeDistanceToActualBaseline(TextBaseline baseline) {
    // returns the baseline of the first cell that has a baseline in the first row
886
    assert(!debugNeedsLayout);
Hixie's avatar
Hixie committed
887 888 889
    return _baselineDistance;
  }

890 891 892 893
  /// Returns the list of [RenderBox] objects that are in the given
  /// column, in row order, starting from the first row.
  ///
  /// This is a lazily-evaluated iterable.
Hixie's avatar
Hixie committed
894 895 896
  Iterable<RenderBox> column(int x) sync* {
    for (int y = 0; y < rows; y += 1) {
      final int xy = x + y * columns;
897
      final RenderBox child = _children[xy];
Hixie's avatar
Hixie committed
898 899 900 901 902
      if (child != null)
        yield child;
    }
  }

903 904 905 906
  /// Returns the list of [RenderBox] objects that are on the given
  /// row, in column order, starting with the first column.
  ///
  /// This is a lazily-evaluated iterable.
Hixie's avatar
Hixie committed
907 908 909 910
  Iterable<RenderBox> row(int y) sync* {
    final int start = y * columns;
    final int end = (y + 1) * columns;
    for (int xy = start; xy < end; xy += 1) {
911
      final RenderBox child = _children[xy];
Hixie's avatar
Hixie committed
912 913 914 915 916
      if (child != null)
        yield child;
    }
  }

917
  List<double> _computeColumnWidths(BoxConstraints constraints) {
918
    assert(constraints != null);
Hixie's avatar
Hixie committed
919
    assert(_children.length == rows * columns);
920 921 922 923 924 925 926 927 928 929 930
    // We apply the constraints to the column widths in the order of
    // least important to most important:
    // 1. apply the ideal widths (maxIntrinsicWidth)
    // 2. grow the flex columns so that the table has the maxWidth (if
    //    finite) or the minWidth (if not)
    // 3. if there were no flex columns, then grow the table to the
    //    minWidth.
    // 4. apply the maximum width of the table, shrinking columns as
    //    necessary, applying minimum column widths as we go

    // 1. apply ideal widths, and collect information we'll need later
Hixie's avatar
Hixie committed
931
    final List<double> widths = new List<double>(columns);
932
    final List<double> minWidths = new List<double>(columns);
Hixie's avatar
Hixie committed
933
    final List<double> flexes = new List<double>(columns);
934 935
    double tableWidth = 0.0; // running tally of the sum of widths[x] for all x
    double unflexedTableWidth = 0.0; // sum of the maxIntrinsicWidths of any column that has null flex
Hixie's avatar
Hixie committed
936 937
    double totalFlex = 0.0;
    for (int x = 0; x < columns; x += 1) {
938 939
      final TableColumnWidth columnWidth = _columnWidths[x] ?? defaultColumnWidth;
      final Iterable<RenderBox> columnCells = column(x);
940 941 942 943 944 945 946 947 948 949 950 951 952
      // apply ideal width (maxIntrinsicWidth)
      final double maxIntrinsicWidth = columnWidth.maxIntrinsicWidth(columnCells, constraints.maxWidth);
      assert(maxIntrinsicWidth.isFinite);
      assert(maxIntrinsicWidth >= 0.0);
      widths[x] = maxIntrinsicWidth;
      tableWidth += maxIntrinsicWidth;
      // collect min width information while we're at it
      final double minIntrinsicWidth = columnWidth.minIntrinsicWidth(columnCells, constraints.maxWidth);
      assert(minIntrinsicWidth.isFinite);
      assert(minIntrinsicWidth >= 0.0);
      minWidths[x] = minIntrinsicWidth;
      assert(maxIntrinsicWidth >= minIntrinsicWidth);
      // collect flex information while we're at it
953
      final double flex = columnWidth.flex(columnCells);
Hixie's avatar
Hixie committed
954
      if (flex != null) {
955 956
        assert(flex.isFinite);
        assert(flex > 0.0);
Hixie's avatar
Hixie committed
957 958
        flexes[x] = flex;
        totalFlex += flex;
959 960
      } else {
        unflexedTableWidth += maxIntrinsicWidth;
Hixie's avatar
Hixie committed
961 962 963
      }
    }
    assert(!widths.any((double value) => value == null));
964 965 966 967 968 969 970 971 972 973
    final double maxWidthConstraint = constraints.maxWidth;
    final double minWidthConstraint = constraints.minWidth;

    // 2. grow the flex columns so that the table has the maxWidth (if
    //    finite) or the minWidth (if not)
    if (totalFlex > 0.0) {
      // this can only grow the table, but it _will_ grow the table at
      // least as big as the target width.
      double targetWidth;
      if (maxWidthConstraint.isFinite) {
974
        targetWidth = maxWidthConstraint;
975 976 977 978 979 980 981
      } else {
        targetWidth = minWidthConstraint;
      }
      if (tableWidth < targetWidth) {
        final double remainingWidth = targetWidth - unflexedTableWidth;
        assert(remainingWidth.isFinite);
        assert(remainingWidth >= 0.0);
Hixie's avatar
Hixie committed
982 983
        for (int x = 0; x < columns; x += 1) {
          if (flexes[x] != null) {
984 985 986 987 988 989 990 991
            final double flexedWidth = remainingWidth * flexes[x] / totalFlex;
            assert(flexedWidth.isFinite);
            assert(flexedWidth >= 0.0);
            if (widths[x] < flexedWidth) {
              final double delta = flexedWidth - widths[x];
              tableWidth += delta;
              widths[x] = flexedWidth;
            }
Hixie's avatar
Hixie committed
992 993
          }
        }
994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047
        assert(tableWidth >= targetWidth);
      }
    } else // step 2 and 3 are mutually exclusive

    // 3. if there were no flex columns, then grow the table to the
    //    minWidth.
    if (tableWidth < minWidthConstraint) {
      final double delta = (minWidthConstraint - tableWidth) / columns;
      for (int x = 0; x < columns; x += 1)
        widths[x] += delta;
      tableWidth = minWidthConstraint;
    }

    // beyond this point, unflexedTableWidth is no longer valid
    assert(() { unflexedTableWidth = null; return true; });

    // 4. apply the maximum width of the table, shrinking columns as
    //    necessary, applying minimum column widths as we go
    if (tableWidth > maxWidthConstraint) {
      double deficit = tableWidth - maxWidthConstraint;
      // Some columns may have low flex but have all the free space.
      // (Consider a case with a 1px wide column of flex 1000.0 and
      // a 1000px wide column of flex 1.0; the sizes coming from the
      // maxIntrinsicWidths. If the maximum table width is 2px, then
      // just applying the flexes to the deficit would result in a
      // table with one column at -998px and one column at 990px,
      // which is wildly unhelpful.)
      // Similarly, some columns may be flexible, but not actually
      // be shrinkable due to a large minimum width. (Consider a
      // case with two columns, one is flex and one isn't, both have
      // 1000px maxIntrinsicWidths, but the flex one has 1000px
      // minIntrinsicWidth also. The whole deficit will have to come
      // from the non-flex column.)
      // So what we do is we repeatedly iterate through the flexible
      // columns shrinking them proportionally until we have no
      // available columns, then do the same to the non-flexible ones.
      int availableColumns = columns;
      while (deficit > 0.0 && totalFlex > 0.0) {
        double newTotalFlex = 0.0;
        for (int x = 0; x < columns; x += 1) {
          if (flexes[x] != null) {
            final double newWidth = widths[x] - deficit * flexes[x] / totalFlex;
            assert(newWidth.isFinite);
            if (newWidth <= minWidths[x]) {
              // shrank to minimum
              deficit -= widths[x] - minWidths[x];
              widths[x] = minWidths[x];
              flexes[x] = null;
              availableColumns -= 1;
            } else {
              deficit -= widths[x] - newWidth;
              widths[x] = newWidth;
              newTotalFlex += flexes[x];
            }
1048
            assert(widths[x] >= 0.0);
1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062
          }
        }
        totalFlex = newTotalFlex;
      }
      if (deficit > 0.0) {
        // Now we have to take out the remaining space from the
        // columns that aren't minimum sized.
        // To make this fair, we repeatedly remove equal amounts from
        // each column, clamped to the minimum width, until we run out
        // of columns that aren't at their minWidth.
        do {
          final double delta = deficit / availableColumns;
          int newAvailableColumns = 0;
          for (int x = 0; x < columns; x += 1) {
1063
            final double availableDelta = widths[x] - minWidths[x];
1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077
            if (availableDelta > 0.0) {
              if (availableDelta <= delta) {
                // shrank to minimum
                deficit -= widths[x] - minWidths[x];
                widths[x] = minWidths[x];
              } else {
                deficit -= availableDelta;
                widths[x] -= availableDelta;
                newAvailableColumns += 1;
              }
            }
          }
          availableColumns = newAvailableColumns;
        } while (deficit > 0.0 && availableColumns > 0);
Hixie's avatar
Hixie committed
1078 1079 1080 1081 1082 1083
      }
    }
    return widths;
  }

  // cache the table geometry for painting purposes
1084
  final List<double> _rowTops = <double>[];
Hixie's avatar
Hixie committed
1085 1086
  List<double> _columnLefts;

1087 1088 1089 1090 1091 1092 1093 1094 1095 1096
  /// Returns the position and dimensions of the box that the given
  /// row covers, in this render object's coordinate space (so the
  /// left coordinate is always 0.0).
  ///
  /// The row being queried must exist.
  ///
  /// This is only valid after layout.
  Rect getRowBox(int row) {
    assert(row >= 0);
    assert(row < rows);
1097
    assert(!debugNeedsLayout);
1098 1099 1100
    return new Rect.fromLTRB(0.0, _rowTops[row], size.width, _rowTops[row + 1]);
  }

Hixie's avatar
Hixie committed
1101 1102
  @override
  void performLayout() {
Hixie's avatar
Hixie committed
1103
    assert(_children.length == rows * columns);
Hixie's avatar
Hixie committed
1104
    if (rows * columns == 0) {
Hixie's avatar
Hixie committed
1105 1106
      // TODO(ianh): if columns is zero, this should be zero width
      // TODO(ianh): if columns is not zero, this should be based on the column width specifications
1107
      size = constraints.constrain(const Size(0.0, 0.0));
Hixie's avatar
Hixie committed
1108 1109
      return;
    }
1110
    final List<double> widths = _computeColumnWidths(constraints);
Hixie's avatar
Hixie committed
1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126
    final List<double> positions = new List<double>(columns);
    _rowTops.clear();
    positions[0] = 0.0;
    for (int x = 1; x < columns; x += 1)
      positions[x] = positions[x-1] + widths[x-1];
    _columnLefts = positions;
    assert(!positions.any((double value) => value == null));
    _baselineDistance = null;
    // then, lay out each row
    double rowTop = 0.0;
    for (int y = 0; y < rows; y += 1) {
      _rowTops.add(rowTop);
      double rowHeight = 0.0;
      bool haveBaseline = false;
      double beforeBaselineDistance = 0.0;
      double afterBaselineDistance = 0.0;
1127
      final List<double> baselines = new List<double>(columns);
Hixie's avatar
Hixie committed
1128 1129
      for (int x = 0; x < columns; x += 1) {
        final int xy = x + y * columns;
1130
        final RenderBox child = _children[xy];
Hixie's avatar
Hixie committed
1131
        if (child != null) {
1132
          final TableCellParentData childParentData = child.parentData;
Hixie's avatar
Hixie committed
1133
          assert(childParentData != null);
Hixie's avatar
Hixie committed
1134 1135
          childParentData.x = x;
          childParentData.y = y;
Hixie's avatar
Hixie committed
1136 1137 1138 1139
          switch (childParentData.verticalAlignment ?? defaultVerticalAlignment) {
            case TableCellVerticalAlignment.baseline:
              assert(textBaseline != null);
              child.layout(new BoxConstraints.tightFor(width: widths[x]), parentUsesSize: true);
1140
              final double childBaseline = child.getDistanceToBaseline(textBaseline, onlyReal: true);
Hixie's avatar
Hixie committed
1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168
              if (childBaseline != null) {
                beforeBaselineDistance = math.max(beforeBaselineDistance, childBaseline);
                afterBaselineDistance = math.max(afterBaselineDistance, child.size.height - childBaseline);
                baselines[x] = childBaseline;
                haveBaseline = true;
              } else {
                rowHeight = math.max(rowHeight, child.size.height);
                childParentData.offset = new Offset(positions[x], rowTop);
              }
              break;
            case TableCellVerticalAlignment.top:
            case TableCellVerticalAlignment.middle:
            case TableCellVerticalAlignment.bottom:
              child.layout(new BoxConstraints.tightFor(width: widths[x]), parentUsesSize: true);
              rowHeight = math.max(rowHeight, child.size.height);
              break;
            case TableCellVerticalAlignment.fill:
              break;
          }
        }
      }
      if (haveBaseline) {
        if (y == 0)
          _baselineDistance = beforeBaselineDistance;
        rowHeight = math.max(rowHeight, beforeBaselineDistance + afterBaselineDistance);
      }
      for (int x = 0; x < columns; x += 1) {
        final int xy = x + y * columns;
1169
        final RenderBox child = _children[xy];
Hixie's avatar
Hixie committed
1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194
        if (child != null) {
          final TableCellParentData childParentData = child.parentData;
          switch (childParentData.verticalAlignment ?? defaultVerticalAlignment) {
            case TableCellVerticalAlignment.baseline:
              if (baselines[x] != null)
                childParentData.offset = new Offset(positions[x], rowTop + beforeBaselineDistance - baselines[x]);
              break;
            case TableCellVerticalAlignment.top:
              childParentData.offset = new Offset(positions[x], rowTop);
              break;
            case TableCellVerticalAlignment.middle:
              childParentData.offset = new Offset(positions[x], rowTop + (rowHeight - child.size.height) / 2.0);
              break;
            case TableCellVerticalAlignment.bottom:
              childParentData.offset = new Offset(positions[x], rowTop + rowHeight - child.size.height);
              break;
            case TableCellVerticalAlignment.fill:
              child.layout(new BoxConstraints.tightFor(width: widths[x], height: rowHeight));
              childParentData.offset = new Offset(positions[x], rowTop);
              break;
          }
        }
      }
      rowTop += rowHeight;
    }
1195
    _rowTops.add(rowTop);
Hixie's avatar
Hixie committed
1196
    size = constraints.constrain(new Size(positions.last + widths.last, rowTop));
1197
    assert(_rowTops.length == rows + 1);
Hixie's avatar
Hixie committed
1198 1199 1200
  }

  @override
1201
  bool hitTestChildren(HitTestResult result, { Offset position }) {
Hixie's avatar
Hixie committed
1202
    assert(_children.length == rows * columns);
Hixie's avatar
Hixie committed
1203
    for (int index = _children.length - 1; index >= 0; index -= 1) {
1204
      final RenderBox child = _children[index];
Hixie's avatar
Hixie committed
1205 1206
      if (child != null) {
        final BoxParentData childParentData = child.parentData;
1207
        if (child.hitTest(result, position: position - childParentData.offset))
Hixie's avatar
Hixie committed
1208 1209 1210 1211 1212 1213 1214 1215
          return true;
      }
    }
    return false;
  }

  @override
  void paint(PaintingContext context, Offset offset) {
1216
    Canvas canvas;
Hixie's avatar
Hixie committed
1217
    assert(_children.length == rows * columns);
Hixie's avatar
Hixie committed
1218 1219
    if (rows * columns == 0)
      return;
1220 1221 1222 1223 1224 1225
    assert(_rowTops.length == rows + 1);
    canvas = context.canvas;
    if (_rowDecorations != null) {
      for (int y = 0; y < rows; y += 1) {
        if (_rowDecorations.length <= y)
          break;
1226
        if (_rowDecorations[y] != null) {
1227 1228 1229 1230 1231 1232
          _rowDecorationPainters[y] ??= _rowDecorations[y].createBoxPainter(markNeedsPaint);
          _rowDecorationPainters[y].paint(
            canvas,
            new Offset(offset.dx, offset.dy + _rowTops[y]),
            configuration.copyWith(size: new Size(size.width, _rowTops[y+1] - _rowTops[y]))
          );
1233
        }
1234 1235
      }
    }
Hixie's avatar
Hixie committed
1236
    for (int index = 0; index < _children.length; index += 1) {
1237
      final RenderBox child = _children[index];
Hixie's avatar
Hixie committed
1238
      if (child != null) {
1239
        final BoxParentData childParentData = child.parentData;
Hixie's avatar
Hixie committed
1240 1241 1242
        context.paintChild(child, childParentData.offset + offset);
      }
    }
1243
    canvas = context.canvas;
1244
    final Rect bounds = offset & size;
Hixie's avatar
Hixie committed
1245 1246 1247
    if (border != null) {
      switch (border.verticalInside.style) {
        case BorderStyle.solid:
1248
          final Paint paint = new Paint()
Hixie's avatar
Hixie committed
1249 1250 1251
            ..color = border.verticalInside.color
            ..strokeWidth = border.verticalInside.width
            ..style = PaintingStyle.stroke;
1252
          final Path path = new Path();
Hixie's avatar
Hixie committed
1253 1254 1255 1256 1257 1258 1259 1260 1261 1262
          for (int x = 1; x < columns; x += 1) {
            path.moveTo(bounds.left + _columnLefts[x], bounds.top);
            path.lineTo(bounds.left + _columnLefts[x], bounds.bottom);
          }
          canvas.drawPath(path, paint);
          break;
        case BorderStyle.none: break;
      }
      switch (border.horizontalInside.style) {
        case BorderStyle.solid:
1263
          final Paint paint = new Paint()
Hixie's avatar
Hixie committed
1264 1265 1266
            ..color = border.horizontalInside.color
            ..strokeWidth = border.horizontalInside.width
            ..style = PaintingStyle.stroke;
1267
          final Path path = new Path();
Hixie's avatar
Hixie committed
1268 1269 1270 1271 1272 1273 1274 1275 1276
          for (int y = 1; y < rows; y += 1) {
            path.moveTo(bounds.left, bounds.top + _rowTops[y]);
            path.lineTo(bounds.right, bounds.top + _rowTops[y]);
          }
          canvas.drawPath(path, paint);
          break;
        case BorderStyle.none: break;
      }
      border.paint(canvas, bounds);
Hixie's avatar
Hixie committed
1277 1278 1279 1280 1281 1282 1283 1284
    }
  }

  @override
  void debugFillDescription(List<String> description) {
    super.debugFillDescription(description);
    if (border != null)
      description.add('border: $border');
1285
    if (_columnWidths.isNotEmpty)
Hixie's avatar
Hixie committed
1286 1287 1288
      description.add('specified column widths: $_columnWidths');
    description.add('default column width: $defaultColumnWidth');
    description.add('table size: $columns\u00D7$rows');
1289 1290
    description.add('column offsets: ${ _columnLefts ?? "unknown" }');
    description.add('row offsets: ${ _rowTops ?? "unknown" }');
Hixie's avatar
Hixie committed
1291 1292 1293 1294
  }

  @override
  String debugDescribeChildren(String prefix) {
1295
    final StringBuffer result = new StringBuffer();
Hixie's avatar
Hixie committed
1296
    result.writeln('$prefix \u2502');
1297
    final int lastIndex = _children.length - 1;
Hixie's avatar
Hixie committed
1298 1299 1300 1301 1302 1303
    if (lastIndex < 0) {
      result.writeln('$prefix \u2514\u2500table is empty');
    } else {
      for (int y = 0; y < rows; y += 1) {
        for (int x = 0; x < columns; x += 1) {
          final int xy = x + y * columns;
1304
          final RenderBox child = _children[xy];
Hixie's avatar
Hixie committed
1305 1306 1307 1308 1309 1310
          if (child != null) {
            if (xy < lastIndex) {
              result.write('${child.toStringDeep("$prefix \u251C\u2500child ($x, $y): ", "$prefix \u2502")}');
            } else {
              result.write('${child.toStringDeep("$prefix \u2514\u2500child ($x, $y): ", "$prefix  ")}');
            }
Hixie's avatar
Hixie committed
1311
          } else {
Hixie's avatar
Hixie committed
1312 1313 1314 1315 1316
            if (xy < lastIndex) {
              result.writeln('$prefix \u251C\u2500child ($x, $y) is null');
            } else {
              result.writeln('$prefix \u2514\u2500child ($x, $y) is null');
            }
Hixie's avatar
Hixie committed
1317 1318 1319 1320 1321 1322 1323
          }
        }
      }
    }
    return result.toString();
  }
}