summaryrefslogtreecommitdiffstats
path: root/layout/tables/nsTableWrapperFrame.cpp
blob: a3e957c4fd97554d40350be4a4a0a49b716d9197 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
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
392
393
394
395
396
397
398
399
400
401
402
403
404
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
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "nsTableWrapperFrame.h"

#include "LayoutConstants.h"
#include "mozilla/ComputedStyle.h"
#include "mozilla/PresShell.h"
#include "nsFrameManager.h"
#include "nsGridContainerFrame.h"
#include "nsTableFrame.h"
#include "nsTableCellFrame.h"
#include "nsStyleConsts.h"
#include "nsPresContext.h"
#include "nsCSSRendering.h"
#include "nsIContent.h"
#include "prinrval.h"
#include "nsGkAtoms.h"
#include "nsHTMLParts.h"
#include "nsDisplayList.h"
#include "nsLayoutUtils.h"
#include "nsIFrameInlines.h"
#include <algorithm>

using namespace mozilla;
using namespace mozilla::layout;

nscoord nsTableWrapperFrame::SynthesizeFallbackBaseline(
    mozilla::WritingMode aWM, BaselineSharingGroup aBaselineGroup) const {
  const auto marginBlockEnd = GetLogicalUsedMargin(aWM).BEnd(aWM);
  if (aWM.IsCentralBaseline()) {
    return (BSize(aWM) + marginBlockEnd) / 2;
  }
  // Our fallback baseline is the block-end margin-edge, with respect to the
  // given writing mode.
  if (aBaselineGroup == BaselineSharingGroup::Last) {
    return -marginBlockEnd;
  }
  return BSize(aWM) + marginBlockEnd;
}

Maybe<nscoord> nsTableWrapperFrame::GetNaturalBaselineBOffset(
    WritingMode aWM, BaselineSharingGroup aBaselineGroup,
    BaselineExportContext aExportContext) const {
  // Baseline is determined by row
  // (https://drafts.csswg.org/css-align-3/#baseline-export). If the row
  // direction is going to be orthogonal to the parent's writing mode, the
  // resulting baseline wouldn't be valid, so we use the fallback baseline
  // instead.
  if (StyleDisplay()->IsContainLayout() ||
      GetWritingMode().IsOrthogonalTo(aWM)) {
    return Nothing{};
  }
  auto* innerTable = InnerTableFrame();
  return innerTable
      ->GetNaturalBaselineBOffset(aWM, aBaselineGroup, aExportContext)
      .map([this, aWM, aBaselineGroup, innerTable](nscoord aBaseline) {
        auto bStart = innerTable->BStart(aWM, mRect.Size());
        if (aBaselineGroup == BaselineSharingGroup::First) {
          return aBaseline + bStart;
        }
        auto bEnd = bStart + innerTable->BSize(aWM);
        return BSize(aWM) - (bEnd - aBaseline);
      });
}

nsTableWrapperFrame::nsTableWrapperFrame(ComputedStyle* aStyle,
                                         nsPresContext* aPresContext,
                                         ClassID aID)
    : nsContainerFrame(aStyle, aPresContext, aID) {}

nsTableWrapperFrame::~nsTableWrapperFrame() = default;

NS_QUERYFRAME_HEAD(nsTableWrapperFrame)
  NS_QUERYFRAME_ENTRY(nsTableWrapperFrame)
NS_QUERYFRAME_TAIL_INHERITING(nsContainerFrame)

#ifdef ACCESSIBILITY
a11y::AccType nsTableWrapperFrame::AccessibleType() {
  return a11y::eHTMLTableType;
}
#endif

void nsTableWrapperFrame::Destroy(DestroyContext& aContext) {
  DestroyAbsoluteFrames(aContext);
  mCaptionFrames.DestroyFrames(aContext);
  nsContainerFrame::Destroy(aContext);
}

const nsFrameList& nsTableWrapperFrame::GetChildList(
    ChildListID aListID) const {
  if (aListID == FrameChildListID::Caption) {
    return mCaptionFrames;
  }

  return nsContainerFrame::GetChildList(aListID);
}

void nsTableWrapperFrame::GetChildLists(nsTArray<ChildList>* aLists) const {
  nsContainerFrame::GetChildLists(aLists);
  mCaptionFrames.AppendIfNonempty(aLists, FrameChildListID::Caption);
}

void nsTableWrapperFrame::SetInitialChildList(ChildListID aListID,
                                              nsFrameList&& aChildList) {
  if (FrameChildListID::Caption == aListID) {
#ifdef DEBUG
    nsIFrame::VerifyDirtyBitSet(aChildList);
    for (nsIFrame* f : aChildList) {
      MOZ_ASSERT(f->GetParent() == this, "Unexpected parent");
    }
#endif
    // the frame constructor already checked for table-caption display type
    MOZ_ASSERT(mCaptionFrames.IsEmpty(),
               "already have child frames in CaptionList");
    mCaptionFrames = std::move(aChildList);
  } else {
    MOZ_ASSERT(FrameChildListID::Principal != aListID ||
                   (aChildList.FirstChild() &&
                    aChildList.FirstChild() == aChildList.LastChild() &&
                    aChildList.FirstChild()->IsTableFrame()),
               "expected a single table frame in principal child list");
    nsContainerFrame::SetInitialChildList(aListID, std::move(aChildList));
  }
}

void nsTableWrapperFrame::AppendFrames(ChildListID aListID,
                                       nsFrameList&& aFrameList) {
  // We only have two child frames: the inner table and a caption frame.
  // The inner frame is provided when we're initialized, and it cannot change
  MOZ_ASSERT(FrameChildListID::Caption == aListID, "unexpected child list");
  MOZ_ASSERT(aFrameList.IsEmpty() || aFrameList.FirstChild()->IsTableCaption(),
             "appending non-caption frame to captionList");
  mCaptionFrames.AppendFrames(nullptr, std::move(aFrameList));

  // Reflow the new caption frame. It's already marked dirty, so
  // just tell the pres shell.
  PresShell()->FrameNeedsReflow(this, IntrinsicDirty::FrameAndAncestors,
                                NS_FRAME_HAS_DIRTY_CHILDREN);
  // The presence of caption frames makes us sort our display
  // list differently, so mark us as changed for the new
  // ordering.
  MarkNeedsDisplayItemRebuild();
}

void nsTableWrapperFrame::InsertFrames(
    ChildListID aListID, nsIFrame* aPrevFrame,
    const nsLineList::iterator* aPrevFrameLine, nsFrameList&& aFrameList) {
  MOZ_ASSERT(FrameChildListID::Caption == aListID, "unexpected child list");
  MOZ_ASSERT(aFrameList.IsEmpty() || aFrameList.FirstChild()->IsTableCaption(),
             "inserting non-caption frame into captionList");
  MOZ_ASSERT(!aPrevFrame || aPrevFrame->GetParent() == this,
             "inserting after sibling frame with different parent");
  mCaptionFrames.InsertFrames(nullptr, aPrevFrame, std::move(aFrameList));

  // Reflow the new caption frame. It's already marked dirty, so
  // just tell the pres shell.
  PresShell()->FrameNeedsReflow(this, IntrinsicDirty::FrameAndAncestors,
                                NS_FRAME_HAS_DIRTY_CHILDREN);
  MarkNeedsDisplayItemRebuild();
}

void nsTableWrapperFrame::RemoveFrame(DestroyContext& aContext,
                                      ChildListID aListID,
                                      nsIFrame* aOldFrame) {
  // We only have two child frames: the inner table and one caption frame.
  // The inner frame can't be removed so this should be the caption
  MOZ_ASSERT(FrameChildListID::Caption == aListID, "can't remove inner frame");

  // Remove the frame and destroy it
  mCaptionFrames.DestroyFrame(aContext, aOldFrame);

  PresShell()->FrameNeedsReflow(this, IntrinsicDirty::FrameAndAncestors,
                                NS_FRAME_HAS_DIRTY_CHILDREN);
  MarkNeedsDisplayItemRebuild();
}

void nsTableWrapperFrame::BuildDisplayList(nsDisplayListBuilder* aBuilder,
                                           const nsDisplayListSet& aLists) {
  // No border or background is painted because they belong to the inner table.
  // The outline belongs to the wrapper frame so it can contain the caption.

  // If there's no caption, take a short cut to avoid having to create
  // the special display list set and then sort it.
  if (mCaptionFrames.IsEmpty()) {
    BuildDisplayListForInnerTable(aBuilder, aLists);
    DisplayOutline(aBuilder, aLists);
    return;
  }

  nsDisplayListCollection set(aBuilder);
  BuildDisplayListForInnerTable(aBuilder, set);

  nsDisplayListSet captionSet(set, set.BlockBorderBackgrounds());
  BuildDisplayListForChild(aBuilder, mCaptionFrames.FirstChild(), captionSet);

  // Now we have to sort everything by content order, since the caption
  // may be somewhere inside the table.
  // We don't sort BlockBorderBackgrounds and BorderBackgrounds because the
  // display items in those lists should stay out of content order in order to
  // follow the rules in https://www.w3.org/TR/CSS21/zindex.html#painting-order
  // and paint the caption background after all of the rest.
  set.Floats()->SortByContentOrder(GetContent());
  set.Content()->SortByContentOrder(GetContent());
  set.PositionedDescendants()->SortByContentOrder(GetContent());
  set.Outlines()->SortByContentOrder(GetContent());
  set.MoveTo(aLists);

  DisplayOutline(aBuilder, aLists);
}

void nsTableWrapperFrame::BuildDisplayListForInnerTable(
    nsDisplayListBuilder* aBuilder, const nsDisplayListSet& aLists) {
  // Just paint the regular children, but the children's background is our
  // true background (there should only be one, the real table)
  nsIFrame* kid = mFrames.FirstChild();
  // The children should be in content order
  while (kid) {
    BuildDisplayListForChild(aBuilder, kid, aLists);
    kid = kid->GetNextSibling();
  }
}

ComputedStyle* nsTableWrapperFrame::GetParentComputedStyle(
    nsIFrame** aProviderFrame) const {
  // The table wrapper frame and the (inner) table frame split the style
  // data by giving the table frame the ComputedStyle associated with
  // the table content node and creating a ComputedStyle for the wrapper
  // frame that is a *child* of the table frame's ComputedStyle,
  // matching the ::-moz-table-wrapper pseudo-element. html.css has a
  // rule that causes that pseudo-element (and thus the wrapper table)
  // to inherit *some* style properties from the table frame.  The
  // children of the table inherit directly from the inner table, and
  // the table wrapper's ComputedStyle is a leaf.

  return (*aProviderFrame = InnerTableFrame())->Style();
}

/* virtual */
nscoord nsTableWrapperFrame::GetMinISize(gfxContext* aRenderingContext) {
  nscoord iSize = nsLayoutUtils::IntrinsicForContainer(
      aRenderingContext, InnerTableFrame(), IntrinsicISizeType::MinISize);
  DISPLAY_MIN_INLINE_SIZE(this, iSize);
  if (mCaptionFrames.NotEmpty()) {
    nscoord capISize = nsLayoutUtils::IntrinsicForContainer(
        aRenderingContext, mCaptionFrames.FirstChild(),
        IntrinsicISizeType::MinISize);
    if (capISize > iSize) {
      iSize = capISize;
    }
  }
  return iSize;
}

/* virtual */
nscoord nsTableWrapperFrame::GetPrefISize(gfxContext* aRenderingContext) {
  nscoord maxISize;
  DISPLAY_PREF_INLINE_SIZE(this, maxISize);

  maxISize = nsLayoutUtils::IntrinsicForContainer(
      aRenderingContext, InnerTableFrame(), IntrinsicISizeType::PrefISize);
  if (mCaptionFrames.NotEmpty()) {
    // Don't let the caption's pref isize expand the table's pref isize.
    const nscoord capMinISize = nsLayoutUtils::IntrinsicForContainer(
        aRenderingContext, mCaptionFrames.FirstChild(),
        IntrinsicISizeType::MinISize);
    maxISize = std::max(maxISize, capMinISize);
  }
  return maxISize;
}

LogicalSize nsTableWrapperFrame::InnerTableShrinkWrapSize(
    gfxContext* aRenderingContext, nsTableFrame* aTableFrame, WritingMode aWM,
    const LogicalSize& aCBSize, nscoord aAvailableISize,
    const StyleSizeOverrides& aSizeOverrides, ComputeSizeFlags aFlags) const {
  MOZ_ASSERT(InnerTableFrame() == aTableFrame);

  AutoMaybeDisableFontInflation an(aTableFrame);

  Maybe<LogicalMargin> collapseBorder;
  Maybe<LogicalMargin> collapsePadding;
  aTableFrame->GetCollapsedBorderPadding(collapseBorder, collapsePadding);

  SizeComputationInput input(aTableFrame, aRenderingContext, aWM,
                             aCBSize.ISize(aWM), collapseBorder,
                             collapsePadding);
  LogicalSize marginSize(aWM);  // Inner table doesn't have any margin
  LogicalSize bpSize = input.ComputedLogicalBorderPadding(aWM).Size(aWM);

  // Note that we pass an empty caption-area here (rather than the caption's
  // actual size). This is fine because:
  //
  // 1) nsTableWrapperFrame::ComputeSize() only uses the size returned by this
  //    method (indirectly via calling nsTableWrapperFrame::ComputeAutoSize())
  //    if it get a aSizeOverrides arg containing any size overrides with
  //    mApplyOverridesVerbatim=true. The aSizeOverrides arg is passed to this
  //    method without any modifications.
  //
  // 2) With 1), that means the aSizeOverrides passing into this method should
  //    be applied to the inner table directly, so we don't need to subtract
  //    caption-area when preparing innerOverrides for
  //    nsTableFrame::ComputeSize().
  StyleSizeOverrides innerOverrides = ComputeSizeOverridesForInnerTable(
      aTableFrame, aSizeOverrides, bpSize, /* aBSizeOccupiedByCaption = */ 0);
  auto size =
      aTableFrame
          ->ComputeSize(aRenderingContext, aWM, aCBSize, aAvailableISize,
                        marginSize, bpSize, innerOverrides, aFlags)
          .mLogicalSize;
  size.ISize(aWM) += bpSize.ISize(aWM);
  if (size.BSize(aWM) != NS_UNCONSTRAINEDSIZE) {
    size.BSize(aWM) += bpSize.BSize(aWM);
  }
  return size;
}

LogicalSize nsTableWrapperFrame::CaptionShrinkWrapSize(
    gfxContext* aRenderingContext, nsIFrame* aCaptionFrame, WritingMode aWM,
    const LogicalSize& aCBSize, nscoord aAvailableISize,
    ComputeSizeFlags aFlags) const {
  MOZ_ASSERT(aCaptionFrame == mCaptionFrames.FirstChild());

  AutoMaybeDisableFontInflation an(aCaptionFrame);

  SizeComputationInput input(aCaptionFrame, aRenderingContext, aWM,
                             aCBSize.ISize(aWM));
  LogicalSize marginSize = input.ComputedLogicalMargin(aWM).Size(aWM);
  LogicalSize bpSize = input.ComputedLogicalBorderPadding(aWM).Size(aWM);

  auto size = aCaptionFrame
                  ->ComputeSize(aRenderingContext, aWM, aCBSize,
                                aAvailableISize, marginSize, bpSize, {}, aFlags)
                  .mLogicalSize;
  size.ISize(aWM) += (marginSize.ISize(aWM) + bpSize.ISize(aWM));
  if (size.BSize(aWM) != NS_UNCONSTRAINEDSIZE) {
    size.BSize(aWM) += (marginSize.BSize(aWM) + bpSize.BSize(aWM));
  }
  return size;
}

StyleSize nsTableWrapperFrame::ReduceStyleSizeBy(
    const StyleSize& aStyleSize, const nscoord aAmountToReduce) const {
  MOZ_ASSERT(aStyleSize.ConvertsToLength(), "Only handles 'Length' StyleSize!");
  const nscoord size = std::max(0, aStyleSize.ToLength() - aAmountToReduce);
  return StyleSize::LengthPercentage(LengthPercentage::FromAppUnits(size));
}

StyleSizeOverrides nsTableWrapperFrame::ComputeSizeOverridesForInnerTable(
    const nsTableFrame* aTableFrame,
    const StyleSizeOverrides& aWrapperSizeOverrides,
    const LogicalSize& aBorderPadding, nscoord aBSizeOccupiedByCaption) const {
  if (aWrapperSizeOverrides.mApplyOverridesVerbatim ||
      !aWrapperSizeOverrides.HasAnyLengthOverrides()) {
    // We are asked to apply the size overrides directly to the inner table, or
    // there's no 'Length' size overrides. No need to tweak the size overrides.
    return aWrapperSizeOverrides;
  }

  const auto wm = aTableFrame->GetWritingMode();
  LogicalSize areaOccupied(wm, 0, aBSizeOccupiedByCaption);
  if (aTableFrame->StylePosition()->mBoxSizing == StyleBoxSizing::Content) {
    // If the inner table frame has 'box-sizing: content', enlarge the occupied
    // area by adding border & padding because they should also be subtracted
    // from the size overrides.
    areaOccupied += aBorderPadding;
  }

  StyleSizeOverrides innerSizeOverrides;
  const auto& wrapperISize = aWrapperSizeOverrides.mStyleISize;
  if (wrapperISize) {
    MOZ_ASSERT(!wrapperISize->HasPercent(),
               "Table doesn't support size overrides containing percentages!");
    innerSizeOverrides.mStyleISize.emplace(
        wrapperISize->ConvertsToLength()
            ? ReduceStyleSizeBy(*wrapperISize, areaOccupied.ISize(wm))
            : *wrapperISize);
  }

  const auto& wrapperBSize = aWrapperSizeOverrides.mStyleBSize;
  if (wrapperBSize) {
    MOZ_ASSERT(!wrapperBSize->HasPercent(),
               "Table doesn't support size overrides containing percentages!");
    innerSizeOverrides.mStyleBSize.emplace(
        wrapperBSize->ConvertsToLength()
            ? ReduceStyleSizeBy(*wrapperBSize, areaOccupied.BSize(wm))
            : *wrapperBSize);
  }

  return innerSizeOverrides;
}

/* virtual */
nsIFrame::SizeComputationResult nsTableWrapperFrame::ComputeSize(
    gfxContext* aRenderingContext, WritingMode aWM, const LogicalSize& aCBSize,
    nscoord aAvailableISize, const LogicalSize& aMargin,
    const LogicalSize& aBorderPadding, const StyleSizeOverrides& aSizeOverrides,
    ComputeSizeFlags aFlags) {
  auto result = nsContainerFrame::ComputeSize(
      aRenderingContext, aWM, aCBSize, aAvailableISize, aMargin, aBorderPadding,
      aSizeOverrides, aFlags);

  if (aSizeOverrides.mApplyOverridesVerbatim &&
      aSizeOverrides.HasAnyOverrides()) {
    // We are asked to apply the size overrides directly to the inner table, but
    // we still want ourselves to remain 'auto'-sized and shrink-wrapping our
    // children's sizes. (Table wrapper frames always have 'auto' inline-size
    // and block-size, since we don't inherit those properties from inner table,
    // and authors can't target them with styling.)
    auto size =
        ComputeAutoSize(aRenderingContext, aWM, aCBSize, aAvailableISize,
                        aMargin, aBorderPadding, aSizeOverrides, aFlags);
    result.mLogicalSize = size;
  }

  return result;
}

/* virtual */
LogicalSize nsTableWrapperFrame::ComputeAutoSize(
    gfxContext* aRenderingContext, WritingMode aWM, const LogicalSize& aCBSize,
    nscoord aAvailableISize, const LogicalSize& aMargin,
    const LogicalSize& aBorderPadding, const StyleSizeOverrides& aSizeOverrides,
    ComputeSizeFlags aFlags) {
  nscoord kidAvailableISize = aAvailableISize - aMargin.ISize(aWM);
  NS_ASSERTION(aBorderPadding.IsAllZero(),
               "Table wrapper frames cannot have borders or paddings");

  // When we're shrink-wrapping, our auto size needs to wrap around the
  // actual size of the table, which (if it is specified as a percent)
  // could be something that is not reflected in our GetMinISize and
  // GetPrefISize.  See bug 349457 for an example.
  const ComputeSizeFlags flags = CreateComputeSizeFlagsForChild();

  // Match the logic in Reflow() that sets aside space for the caption.
  Maybe<StyleCaptionSide> captionSide = GetCaptionSide();

  const LogicalSize innerTableSize = InnerTableShrinkWrapSize(
      aRenderingContext, InnerTableFrame(), aWM, aCBSize, kidAvailableISize,
      aSizeOverrides, flags);
  if (!captionSide) {
    return innerTableSize;
  }
  const LogicalSize captionSize =
      CaptionShrinkWrapSize(aRenderingContext, mCaptionFrames.FirstChild(), aWM,
                            aCBSize, innerTableSize.ISize(aWM), flags);
  const nscoord iSize =
      std::max(innerTableSize.ISize(aWM), captionSize.ISize(aWM));
  nscoord bSize = NS_UNCONSTRAINEDSIZE;
  if (innerTableSize.BSize(aWM) != NS_UNCONSTRAINEDSIZE &&
      captionSize.BSize(aWM) != NS_UNCONSTRAINEDSIZE) {
    bSize = innerTableSize.BSize(aWM) + captionSize.BSize(aWM);
  }
  return LogicalSize(aWM, iSize, bSize);
}

Maybe<StyleCaptionSide> nsTableWrapperFrame::GetCaptionSide() const {
  if (mCaptionFrames.IsEmpty()) {
    return Nothing();
  }
  return Some(mCaptionFrames.FirstChild()->StyleTableBorder()->mCaptionSide);
}

StyleVerticalAlignKeyword nsTableWrapperFrame::GetCaptionVerticalAlign() const {
  const auto& va = mCaptionFrames.FirstChild()->StyleDisplay()->mVerticalAlign;
  return va.IsKeyword() ? va.AsKeyword() : StyleVerticalAlignKeyword::Top;
}

nscoord nsTableWrapperFrame::ComputeFinalBSize(
    const LogicalSize& aInnerSize, const LogicalSize& aCaptionSize,
    const LogicalMargin& aCaptionMargin, const WritingMode aWM) const {
  // negative sizes can upset overflow-area code
  return std::max(0, aInnerSize.BSize(aWM) +
                         std::max(0, aCaptionSize.BSize(aWM) +
                                         aCaptionMargin.BStartEnd(aWM)));
}

void nsTableWrapperFrame::GetCaptionOrigin(StyleCaptionSide aCaptionSide,
                                           const LogicalSize& aInnerSize,
                                           const LogicalSize& aCaptionSize,
                                           LogicalMargin& aCaptionMargin,
                                           LogicalPoint& aOrigin,
                                           WritingMode aWM) const {
  aOrigin.I(aWM) = aOrigin.B(aWM) = 0;
  if ((NS_UNCONSTRAINEDSIZE == aInnerSize.ISize(aWM)) ||
      (NS_UNCONSTRAINEDSIZE == aInnerSize.BSize(aWM)) ||
      (NS_UNCONSTRAINEDSIZE == aCaptionSize.ISize(aWM)) ||
      (NS_UNCONSTRAINEDSIZE == aCaptionSize.BSize(aWM))) {
    return;
  }
  if (mCaptionFrames.IsEmpty()) {
    return;
  }

  NS_ASSERTION(NS_AUTOMARGIN != aCaptionMargin.IStart(aWM) &&
                   NS_AUTOMARGIN != aCaptionMargin.BStart(aWM) &&
                   NS_AUTOMARGIN != aCaptionMargin.BEnd(aWM),
               "The computed caption margin is auto?");

  aOrigin.I(aWM) = aCaptionMargin.IStart(aWM);

  // block-dir computation
  switch (aCaptionSide) {
    case StyleCaptionSide::Bottom:
      aOrigin.B(aWM) = aInnerSize.BSize(aWM) + aCaptionMargin.BStart(aWM);
      break;
    case StyleCaptionSide::Top:
      aOrigin.B(aWM) = aCaptionMargin.BStart(aWM);
      break;
  }
}

void nsTableWrapperFrame::GetInnerOrigin(const MaybeCaptionSide& aCaptionSide,
                                         const LogicalSize& aCaptionSize,
                                         const LogicalMargin& aCaptionMargin,
                                         const LogicalSize& aInnerSize,
                                         LogicalPoint& aOrigin,
                                         WritingMode aWM) const {
  NS_ASSERTION(NS_AUTOMARGIN != aCaptionMargin.IStart(aWM) &&
                   NS_AUTOMARGIN != aCaptionMargin.IEnd(aWM),
               "The computed caption margin is auto?");

  aOrigin.I(aWM) = aOrigin.B(aWM) = 0;
  if ((NS_UNCONSTRAINEDSIZE == aInnerSize.ISize(aWM)) ||
      (NS_UNCONSTRAINEDSIZE == aInnerSize.BSize(aWM)) ||
      (NS_UNCONSTRAINEDSIZE == aCaptionSize.ISize(aWM)) ||
      (NS_UNCONSTRAINEDSIZE == aCaptionSize.BSize(aWM))) {
    return;
  }

  // block-dir computation
  if (aCaptionSide) {
    switch (*aCaptionSide) {
      case StyleCaptionSide::Bottom:
        // Leave at zero.
        break;
      case StyleCaptionSide::Top:
        aOrigin.B(aWM) =
            aCaptionSize.BSize(aWM) + aCaptionMargin.BStartEnd(aWM);
        break;
    }
  }
}

ComputeSizeFlags nsTableWrapperFrame::CreateComputeSizeFlagsForChild() const {
  // Shrink-wrap child frames by default, except if we're a stretched grid item.
  if (MOZ_UNLIKELY(IsGridItem())) {
    auto* gridContainer = static_cast<nsGridContainerFrame*>(GetParent());
    if (gridContainer->GridItemShouldStretch(this, eLogicalAxisInline)) {
      return {};
    }
  }
  return {ComputeSizeFlag::ShrinkWrap};
}

void nsTableWrapperFrame::CreateReflowInputForInnerTable(
    nsPresContext* aPresContext, nsTableFrame* aTableFrame,
    const ReflowInput& aOuterRI, Maybe<ReflowInput>& aChildRI,
    const nscoord aAvailISize, nscoord aBSizeOccupiedByCaption) const {
  MOZ_ASSERT(InnerTableFrame() == aTableFrame);

  const WritingMode wm = aTableFrame->GetWritingMode();
  // If we have a caption occupied our content-box area, reduce the available
  // block-size by the amount.
  nscoord availBSize = aOuterRI.AvailableBSize();
  if (availBSize != NS_UNCONSTRAINEDSIZE) {
    availBSize = std::max(0, availBSize - aBSizeOccupiedByCaption);
  }
  const LogicalSize availSize(wm, aAvailISize, availBSize);

  // For inner table frames, the containing block is the same as for the outer
  // table frame.
  Maybe<LogicalSize> cbSize = Some(aOuterRI.mContainingBlockSize);

  // However, if we are a grid item, the CB size needs to subtract our margins
  // and the area occupied by the caption.
  //
  // Note that inner table computed margins are always zero, they're inherited
  // by the table wrapper, so we need to get our margin from aOuterRI.
  if (IsGridItem()) {
    const LogicalMargin margin = aOuterRI.ComputedLogicalMargin(wm);
    cbSize->ISize(wm) = std::max(0, cbSize->ISize(wm) - margin.IStartEnd(wm));
    if (cbSize->BSize(wm) != NS_UNCONSTRAINEDSIZE) {
      cbSize->BSize(wm) = std::max(0, cbSize->BSize(wm) - margin.BStartEnd(wm) -
                                          aBSizeOccupiedByCaption);
    }
  }

  ComputeSizeFlags csFlags = CreateComputeSizeFlagsForChild();
  if (!aTableFrame->IsBorderCollapse() &&
      !aOuterRI.mStyleSizeOverrides.HasAnyOverrides()) {
    // We are not border-collapsed and not given any size overrides. It's
    // sufficient to call the standard ReflowInput constructor.
    aChildRI.emplace(aPresContext, aOuterRI, aTableFrame, availSize, cbSize,
                     ReflowInput::InitFlags{}, StyleSizeOverrides{}, csFlags);
    return;
  }

  Maybe<LogicalMargin> borderPadding;
  Maybe<LogicalMargin> padding;
  {
    // Compute inner table frame's border & padding because we may need to
    // reduce the size for inner table's size overrides. We won't waste time if
    // they are not used, because we can use them directly by passing them into
    // ReflowInput::Init().
    Maybe<LogicalMargin> collapseBorder;
    Maybe<LogicalMargin> collapsePadding;
    aTableFrame->GetCollapsedBorderPadding(collapseBorder, collapsePadding);
    SizeComputationInput input(aTableFrame, aOuterRI.mRenderingContext, wm,
                               cbSize->ISize(wm), collapseBorder,
                               collapsePadding);
    borderPadding.emplace(input.ComputedLogicalBorderPadding(wm));
    padding.emplace(input.ComputedLogicalPadding(wm));
  }

  StyleSizeOverrides innerOverrides = ComputeSizeOverridesForInnerTable(
      aTableFrame, aOuterRI.mStyleSizeOverrides, borderPadding->Size(wm),
      aBSizeOccupiedByCaption);

  aChildRI.emplace(aPresContext, aOuterRI, aTableFrame, availSize, Nothing(),
                   ReflowInput::InitFlag::CallerWillInit, innerOverrides,
                   csFlags);
  aChildRI->Init(aPresContext, cbSize, Some(*borderPadding - *padding),
                 padding);
}

void nsTableWrapperFrame::CreateReflowInputForCaption(
    nsPresContext* aPresContext, nsIFrame* aCaptionFrame,
    const ReflowInput& aOuterRI, Maybe<ReflowInput>& aChildRI,
    const nscoord aAvailISize) const {
  MOZ_ASSERT(aCaptionFrame == mCaptionFrames.FirstChild());

  const WritingMode wm = aCaptionFrame->GetWritingMode();

  // Use unconstrained available block-size so that the caption is always
  // fully-complete.
  const LogicalSize availSize(wm, aAvailISize, NS_UNCONSTRAINEDSIZE);
  aChildRI.emplace(aPresContext, aOuterRI, aCaptionFrame, availSize);

  // See if we need to reset mIsTopOfPage flag.
  if (aChildRI->mFlags.mIsTopOfPage) {
    if (auto captionSide = GetCaptionSide()) {
      if (*captionSide == StyleCaptionSide::Bottom) {
        aChildRI->mFlags.mIsTopOfPage = false;
      }
    }
  }
}

void nsTableWrapperFrame::ReflowChild(nsPresContext* aPresContext,
                                      nsIFrame* aChildFrame,
                                      const ReflowInput& aChildRI,
                                      ReflowOutput& aMetrics,
                                      nsReflowStatus& aStatus) {
  // Using zero as containerSize here because we want consistency between
  // the GetLogicalPosition and ReflowChild calls, to avoid unnecessarily
  // changing the frame's coordinates; but we don't yet know its final
  // position anyway so the actual value is unimportant.
  const nsSize zeroCSize;
  WritingMode wm = aChildRI.GetWritingMode();

  // Use the current position as a best guess for placement.
  LogicalPoint childPt = aChildFrame->GetLogicalPosition(wm, zeroCSize);
  ReflowChildFlags flags = ReflowChildFlags::NoMoveFrame;

  // We don't want to delete our next-in-flow's child if it's an inner table
  // frame, because table wrapper frames always assume that their inner table
  // frames don't go away. If a table wrapper frame is removed because it is
  // a next-in-flow of an already complete table wrapper frame, then it will
  // take care of removing it's inner table frame.
  if (aChildFrame == InnerTableFrame()) {
    flags |= ReflowChildFlags::NoDeleteNextInFlowChild;
  }

  nsContainerFrame::ReflowChild(aChildFrame, aPresContext, aMetrics, aChildRI,
                                wm, childPt, zeroCSize, flags, aStatus);
}

void nsTableWrapperFrame::UpdateOverflowAreas(ReflowOutput& aMet) {
  aMet.SetOverflowAreasToDesiredBounds();
  ConsiderChildOverflow(aMet.mOverflowAreas, InnerTableFrame());
  if (mCaptionFrames.NotEmpty()) {
    ConsiderChildOverflow(aMet.mOverflowAreas, mCaptionFrames.FirstChild());
  }
}

void nsTableWrapperFrame::Reflow(nsPresContext* aPresContext,
                                 ReflowOutput& aDesiredSize,
                                 const ReflowInput& aOuterRI,
                                 nsReflowStatus& aStatus) {
  MarkInReflow();
  DO_GLOBAL_REFLOW_COUNT("nsTableWrapperFrame");
  DISPLAY_REFLOW(aPresContext, this, aOuterRI, aDesiredSize, aStatus);
  MOZ_ASSERT(aStatus.IsEmpty(), "Caller should pass a fresh reflow status!");

  // Initialize out parameters
  aDesiredSize.ClearSize();

  if (!HasAnyStateBits(NS_FRAME_FIRST_REFLOW)) {
    // Set up our kids.  They're already present, on an overflow list,
    // or there are none so we'll create them now
    MoveOverflowToChildList();
  }

  Maybe<ReflowInput> captionRI;
  Maybe<ReflowInput> innerRI;

  nsRect origCaptionRect;
  nsRect origCaptionInkOverflow;
  bool captionFirstReflow = false;
  if (mCaptionFrames.NotEmpty()) {
    origCaptionRect = mCaptionFrames.FirstChild()->GetRect();
    origCaptionInkOverflow = mCaptionFrames.FirstChild()->InkOverflowRect();
    captionFirstReflow =
        mCaptionFrames.FirstChild()->HasAnyStateBits(NS_FRAME_FIRST_REFLOW);
  }

  // ComputeAutoSize has to match this logic.
  WritingMode wm = aOuterRI.GetWritingMode();
  Maybe<StyleCaptionSide> captionSide = GetCaptionSide();
  const nscoord contentBoxISize = aOuterRI.ComputedSize(wm).ISize(wm);

  MOZ_ASSERT(mCaptionFrames.NotEmpty() == captionSide.isSome());

  // Compute the table's size first, and then prevent the caption from
  // being larger in the inline dir unless it has to be.
  //
  // Note that CSS 2.1 (but not 2.0) says:
  //   The width of the anonymous box is the border-edge width of the
  //   table box inside it
  // We don't actually make our anonymous box that isize (if we did,
  // it would break 'auto' margins), but this effectively does that.
  CreateReflowInputForInnerTable(aPresContext, InnerTableFrame(), aOuterRI,
                                 innerRI, contentBoxISize);

  // First reflow the caption.
  ReflowOutput captionMet(wm);
  LogicalSize captionSize(wm);
  LogicalMargin captionMargin(wm);
  if (captionSide) {
    // It's good that CSS 2.1 says not to include margins, since we can't, since
    // they already been converted so they exactly fill the available isize
    // (ignoring the margin on one side if neither are auto).  (We take
    // advantage of that later when we call GetCaptionOrigin, though.)
    nscoord innerBorderISize =
        innerRI->ComputedSizeWithBorderPadding(wm).ISize(wm);
    CreateReflowInputForCaption(aPresContext, mCaptionFrames.FirstChild(),
                                aOuterRI, captionRI, innerBorderISize);

    // We intentionally don't merge capStatus into aStatus, since we currently
    // can't handle caption continuations, but we probably should.
    nsReflowStatus capStatus;
    ReflowChild(aPresContext, mCaptionFrames.FirstChild(), *captionRI,
                captionMet, capStatus);
    captionSize = captionMet.Size(wm);
    captionMargin = captionRI->ComputedLogicalMargin(wm);
    nscoord bSizeOccupiedByCaption =
        captionSize.BSize(wm) + captionMargin.BStartEnd(wm);
    if (bSizeOccupiedByCaption) {
      // Reset the inner table's ReflowInput to reduce various sizes because of
      // the area occupied by caption.
      innerRI.reset();
      CreateReflowInputForInnerTable(aPresContext, InnerTableFrame(), aOuterRI,
                                     innerRI, contentBoxISize,
                                     bSizeOccupiedByCaption);
    }
  }

  // Now we know how much to reduce the block-size for the inner table to
  // account for captions. Reflow the inner table.
  ReflowOutput innerMet(innerRI->GetWritingMode());
  ReflowChild(aPresContext, InnerTableFrame(), *innerRI, innerMet, aStatus);
  LogicalSize innerSize(wm, innerMet.ISize(wm), innerMet.BSize(wm));

  // Now that we've reflowed both we can place them.
  // Compute the desiredSize so that we can use it as the containerSize
  // for the FinishReflowChild calls below.
  LogicalSize desiredSize(wm);

  // We have zero border and padding, so content-box inline-size is our desired
  // border-box inline-size.
  desiredSize.ISize(wm) = contentBoxISize;
  desiredSize.BSize(wm) =
      ComputeFinalBSize(innerSize, captionSize, captionMargin, wm);

  aDesiredSize.SetSize(wm, desiredSize);
  nsSize containerSize = aDesiredSize.PhysicalSize();

  MOZ_ASSERT(mCaptionFrames.NotEmpty() == captionSide.isSome());
  if (mCaptionFrames.NotEmpty()) {
    LogicalPoint captionOrigin(wm);
    GetCaptionOrigin(*captionSide, innerSize, captionSize, captionMargin,
                     captionOrigin, wm);
    FinishReflowChild(mCaptionFrames.FirstChild(), aPresContext, captionMet,
                      captionRI.ptr(), wm, captionOrigin, containerSize,
                      ReflowChildFlags::ApplyRelativePositioning);
    captionRI.reset();
  }
  // XXX If the bsize is constrained then we need to check whether
  // everything still fits...

  LogicalPoint innerOrigin(wm);
  GetInnerOrigin(captionSide, captionSize, captionMargin, innerSize,
                 innerOrigin, wm);
  // NOTE: Relative positioning on the table applies to the whole table wrapper.
  FinishReflowChild(InnerTableFrame(), aPresContext, innerMet, innerRI.ptr(),
                    wm, innerOrigin, containerSize, ReflowChildFlags::Default);
  innerRI.reset();

  if (mCaptionFrames.NotEmpty()) {
    nsTableFrame::InvalidateTableFrame(mCaptionFrames.FirstChild(),
                                       origCaptionRect, origCaptionInkOverflow,
                                       captionFirstReflow);
  }

  UpdateOverflowAreas(aDesiredSize);

  if (GetPrevInFlow()) {
    ReflowOverflowContainerChildren(aPresContext, aOuterRI,
                                    aDesiredSize.mOverflowAreas,
                                    ReflowChildFlags::Default, aStatus);
  }

  FinishReflowWithAbsoluteFrames(aPresContext, aDesiredSize, aOuterRI, aStatus);
}

/* ----- global methods ----- */

nsIContent* nsTableWrapperFrame::GetCellAt(uint32_t aRowIdx,
                                           uint32_t aColIdx) const {
  nsTableCellMap* cellMap = InnerTableFrame()->GetCellMap();
  if (!cellMap) {
    return nullptr;
  }

  nsTableCellFrame* cell = cellMap->GetCellInfoAt(aRowIdx, aColIdx);
  if (!cell) {
    return nullptr;
  }

  return cell->GetContent();
}

nsTableWrapperFrame* NS_NewTableWrapperFrame(PresShell* aPresShell,
                                             ComputedStyle* aStyle) {
  return new (aPresShell)
      nsTableWrapperFrame(aStyle, aPresShell->GetPresContext());
}

NS_IMPL_FRAMEARENA_HELPERS(nsTableWrapperFrame)

#ifdef DEBUG_FRAME_DUMP
nsresult nsTableWrapperFrame::GetFrameName(nsAString& aResult) const {
  return MakeFrameName(u"TableWrapper"_ns, aResult);
}
#endif