/
view_transition_style_tracker.cc
1866 lines (1608 loc) · 69.8 KB
/
view_transition_style_tracker.cc
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
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/renderer/core/view_transition/view_transition_style_tracker.h"
#include <limits>
#include "base/containers/contains.h"
#include "components/viz/common/view_transition_element_resource_id.h"
#include "third_party/blink/public/resources/grit/blink_resources.h"
#include "third_party/blink/renderer/core/animation/element_animations.h"
#include "third_party/blink/renderer/core/css/properties/computed_style_utils.h"
#include "third_party/blink/renderer/core/css/style_change_reason.h"
#include "third_party/blink/renderer/core/css/style_engine.h"
#include "third_party/blink/renderer/core/display_lock/display_lock_document_state.h"
#include "third_party/blink/renderer/core/dom/node.h"
#include "third_party/blink/renderer/core/dom/node_computed_style.h"
#include "third_party/blink/renderer/core/dom/pseudo_element.h"
#include "third_party/blink/renderer/core/frame/browser_controls.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/inspector/console_message.h"
#include "third_party/blink/renderer/core/layout/layout_view.h"
#include "third_party/blink/renderer/core/layout/layout_view_transition_root.h"
#include "third_party/blink/renderer/core/page/page.h"
#include "third_party/blink/renderer/core/page/page_animator.h"
#include "third_party/blink/renderer/core/paint/clip_path_clipper.h"
#include "third_party/blink/renderer/core/paint/paint_layer.h"
#include "third_party/blink/renderer/core/paint/paint_layer_paint_order_iterator.h"
#include "third_party/blink/renderer/core/resize_observer/resize_observer_entry.h"
#include "third_party/blink/renderer/core/scroll/scrollable_area.h"
#include "third_party/blink/renderer/core/style/computed_style_constants.h"
#include "third_party/blink/renderer/core/style/shape_clip_path_operation.h"
#include "third_party/blink/renderer/core/view_transition/view_transition_content_element.h"
#include "third_party/blink/renderer/core/view_transition/view_transition_pseudo_element_base.h"
#include "third_party/blink/renderer/core/view_transition/view_transition_style_builder.h"
#include "third_party/blink/renderer/core/view_transition/view_transition_supplement.h"
#include "third_party/blink/renderer/core/view_transition/view_transition_utils.h"
#include "third_party/blink/renderer/platform/data_resource_helper.h"
#include "third_party/blink/renderer/platform/graphics/paint/geometry_mapper.h"
#include "third_party/blink/renderer/platform/widget/frame_widget.h"
#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
#include "ui/display/screen_info.h"
#include "ui/gfx/geometry/rect_conversions.h"
#include "ui/gfx/geometry/size_conversions.h"
#include "ui/gfx/geometry/transform.h"
namespace blink {
namespace {
const char* kDuplicateTagBaseError =
"Unexpected duplicate view-transition-name: ";
const String& StaticUAStyles() {
DEFINE_STATIC_LOCAL(
String, kStaticUAStyles,
(UncompressResourceAsASCIIString(IDR_UASTYLE_TRANSITION_CSS)));
return kStaticUAStyles;
}
const String& AnimationUAStyles() {
DEFINE_STATIC_LOCAL(
String, kAnimationUAStyles,
(UncompressResourceAsASCIIString(IDR_UASTYLE_TRANSITION_ANIMATIONS_CSS)));
return kAnimationUAStyles;
}
// Computes and returns the start offset for element's painting in horizontal or
// vertical direction.
// `start` and `end` denote the offset where the element's ink overflow
// rectangle start and end for a particular direction, relative to the element's
// border box.
// `snapshot_root_dimension` is the length of the snapshot root in the same
// direction.
// `max_capture_size` denotes the maximum bounds we can capture for an element.
float ComputeStartForSide(float start,
float end,
int snapshot_root_dimension,
int max_capture_size) {
DCHECK_GT((end - start), max_capture_size)
<< "Side must be larger than max texture size";
DCHECK_GE(max_capture_size, snapshot_root_dimension)
<< "Snapshot root bounds must be a subset of max texture size";
// In all comments below, | and _ denote the edges for the snapshot root and
// * denote the edges of the element being captured.
// This is for the following cases:
// ____________
// | |
// | ****** |
// |__*____*____|
// * *
// ******
//
// The element starts after the left edge horizontally or after the top edge
// vertically and is partially onscreen.
// ____________
// | |
// | |
// |____________|
//
// ******
// * *
// ******
//
// The element starts after the left edge horizontally or after the top edge
// vertically and is completely offscreen.
//
// For both these cases, start painting from the left or top edge.
if (start > 0) {
return start;
}
// This is for the following cases:
// ******
// __*____*____
// | * * |
// | ****** |
// |____________|
//
// The element ends before the right edge horizontally or before the bottom
// edge vertically and is partially onscreen.
//
// ******
// * *
// ******
// ____________
// | |
// | |
// |____________|
//
// The element ends before the right edge horizontally or before the bottom
// edge vertically and is completely offscreen.
//
// For both these cases, start painting from the right or bottom edge.
if (end < snapshot_root_dimension) {
return end - max_capture_size;
}
// This is for the following case:
// ******
// __*____*____
// | * * |
// | * * |
// |__*____*____|
// * *
// ******
//
// The element covers the complete snapshot root horizontally or vertically
// and is partially offscreen on both sides.
//
// Capture the element's intersection with the snapshot root, inflating it by
// the remaining margin on both sides. If a side doesn't consume the margin
// completely, give the remaining capacity to the other side.
const float delta_to_distribute_per_side =
(max_capture_size - snapshot_root_dimension) / 2;
const float delta_on_end_side = end - snapshot_root_dimension;
const float delta_for_start_side =
delta_to_distribute_per_side +
std::max(0.f, (delta_to_distribute_per_side - delta_on_end_side));
return std::max(start, -delta_for_start_side);
}
// Computes the subset of an element's `ink_overflow_rect_in_border_box_space`
// that should be painted. The return value is relative to the element's border
// box.
// Returns null if the complete ink overflow rect should be painted.
absl::optional<gfx::RectF> ComputeCaptureRect(
const int max_capture_size,
const PhysicalRect& ink_overflow_rect_in_border_box_space,
const gfx::Transform& element_to_snapshot_root,
const gfx::Size& snapshot_root_size) {
if (ink_overflow_rect_in_border_box_space.Width() <= max_capture_size &&
ink_overflow_rect_in_border_box_space.Height() <= max_capture_size) {
return absl::nullopt;
}
// Compute the matrix to map the element's ink overflow rectangle to snapshot
// root's coordinate space. This is required to figure out which subset of the
// element to paint based on its position in the viewport.
// If the transform is not invertible, fallback to painting from the element's
// ink overflow rectangle's origin.
gfx::Transform snapshot_root_to_element;
if (!element_to_snapshot_root.GetInverse(&snapshot_root_to_element)) {
gfx::SizeF size(ink_overflow_rect_in_border_box_space.size);
size.SetToMin(gfx::SizeF(max_capture_size, max_capture_size));
return gfx::RectF(gfx::PointF(ink_overflow_rect_in_border_box_space.offset),
size);
}
const gfx::RectF ink_overflow_rect_in_snapshot_root_space =
element_to_snapshot_root.MapRect(
gfx::RectF(ink_overflow_rect_in_border_box_space));
gfx::RectF captured_ink_overflow_subrect_in_snapshot_root_space =
ink_overflow_rect_in_snapshot_root_space;
if (ink_overflow_rect_in_snapshot_root_space.width() > max_capture_size) {
captured_ink_overflow_subrect_in_snapshot_root_space.set_x(
ComputeStartForSide(ink_overflow_rect_in_snapshot_root_space.x(),
ink_overflow_rect_in_snapshot_root_space.right(),
snapshot_root_size.width(), max_capture_size));
captured_ink_overflow_subrect_in_snapshot_root_space.set_width(
max_capture_size);
}
if (ink_overflow_rect_in_snapshot_root_space.height() > max_capture_size) {
captured_ink_overflow_subrect_in_snapshot_root_space.set_y(
ComputeStartForSide(ink_overflow_rect_in_snapshot_root_space.y(),
ink_overflow_rect_in_snapshot_root_space.bottom(),
snapshot_root_size.height(), max_capture_size));
captured_ink_overflow_subrect_in_snapshot_root_space.set_height(
max_capture_size);
}
return snapshot_root_to_element.MapRect(
captured_ink_overflow_subrect_in_snapshot_root_space);
}
int ComputeMaxCaptureSize(absl::optional<int> max_texture_size,
const gfx::Size& snapshot_root_size) {
// While we can render up to the max texture size, that would significantly
// add to the memory overhead. So limit to up to a viewport worth of
// additional content.
const int max_bounds_based_on_viewport =
2 * std::max(snapshot_root_size.width(), snapshot_root_size.height());
// If the max texture size is not known yet, clip to the size of the snapshot
// root. The snapshot root corresponds to the maximum screen bounds, we must
// be able to allocate a buffer of that size.
const int computed_max_texture_size = max_texture_size.value_or(
std::max(snapshot_root_size.width(), snapshot_root_size.height()));
DCHECK_LE(snapshot_root_size.width(), computed_max_texture_size);
DCHECK_LE(snapshot_root_size.height(), computed_max_texture_size);
return std::min(max_bounds_based_on_viewport, computed_max_texture_size);
}
gfx::Transform ComputeViewportTransform(const LayoutObject& object) {
DCHECK(object.HasLayer());
DCHECK(!object.IsLayoutView());
auto& first_fragment = object.FirstFragment();
DCHECK(ToRoundedPoint(first_fragment.PaintOffset()).IsOrigin())
<< first_fragment.PaintOffset();
auto paint_properties = first_fragment.LocalBorderBoxProperties();
auto& root_fragment = object.GetDocument().GetLayoutView()->FirstFragment();
const auto& root_properties = root_fragment.LocalBorderBoxProperties();
auto transform = GeometryMapper::SourceToDestinationProjection(
paint_properties.Transform(), root_properties.Transform());
if (!transform.HasPerspective()) {
transform.Round2dTranslationComponents();
}
return transform;
}
gfx::Transform ConvertFromTopLeftToCenter(
const gfx::Transform& transform_from_top_left,
const PhysicalSize& box_size) {
gfx::Transform transform_from_center;
transform_from_center.Translate(-box_size.width / 2, -box_size.height / 2);
transform_from_center.PreConcat(transform_from_top_left);
transform_from_center.Translate(box_size.width / 2, box_size.height / 2);
return transform_from_center;
}
float DevicePixelRatioFromDocument(Document& document) {
// Prefer to use the effective zoom. This should be the case in most
// situations, unless the transition is being started before first layout
// where documentElement gets a layout object.
if (document.documentElement() &&
document.documentElement()->GetLayoutObject()) {
return document.documentElement()
->GetLayoutObject()
->StyleRef()
.EffectiveZoom();
}
if (!document.GetPage() || !document.GetFrame()) {
return 0.f;
}
return document.GetPage()
->GetChromeClient()
.GetScreenInfo(*document.GetFrame())
.device_scale_factor;
}
} // namespace
class ViewTransitionStyleTracker::ImageWrapperPseudoElement
: public ViewTransitionPseudoElementBase {
public:
ImageWrapperPseudoElement(Element* parent,
PseudoId pseudo_id,
const AtomicString& view_transition_name,
const ViewTransitionStyleTracker* style_tracker)
: ViewTransitionPseudoElementBase(parent,
pseudo_id,
view_transition_name,
style_tracker) {}
~ImageWrapperPseudoElement() override = default;
private:
bool CanGeneratePseudoElement(PseudoId pseudo_id) const override {
if (!ViewTransitionPseudoElementBase::CanGeneratePseudoElement(pseudo_id)) {
return false;
}
// If we're being called with a name, we must have a tracking for this name.
auto it = style_tracker_->element_data_map_.find(view_transition_name());
CHECK(it != style_tracker_->element_data_map_.end());
const auto& element_data = it->value;
if (pseudo_id == kPseudoIdViewTransitionOld) {
return element_data->old_snapshot_id.IsValid();
} else if (pseudo_id == kPseudoIdViewTransitionNew) {
return element_data->new_snapshot_id.IsValid();
}
// Image wrapper pseudo-elements can only generate old/new image
// pseudo-elements.
return false;
}
};
ViewTransitionStyleTracker::ViewTransitionStyleTracker(Document& document)
: document_(document),
device_pixel_ratio_(DevicePixelRatioFromDocument(document)) {}
ViewTransitionStyleTracker::ViewTransitionStyleTracker(
Document& document,
ViewTransitionState transition_state)
: document_(document), state_(State::kCaptured), deserialized_(true) {
device_pixel_ratio_ = transition_state.device_pixel_ratio;
captured_name_count_ = static_cast<int>(transition_state.elements.size());
snapshot_root_size_at_capture_ =
transition_state.snapshot_root_size_at_capture;
VectorOf<AtomicString> transition_names;
transition_names.ReserveInitialCapacity(captured_name_count_);
for (const auto& transition_state_element : transition_state.elements) {
auto name =
AtomicString::FromUTF8(transition_state_element.tag_name.c_str());
transition_names.push_back(name);
DCHECK(!element_data_map_.Contains(name));
auto* element_data = MakeGarbageCollected<ElementData>();
element_data->container_properties.emplace_back(
PhysicalSize::FromSizeFFloor(
transition_state_element.border_box_size_in_css_space),
transition_state_element.viewport_matrix);
element_data->old_snapshot_id = transition_state_element.snapshot_id;
element_data->element_index = transition_state_element.paint_order;
set_element_sequence_id_ = std::max(set_element_sequence_id_,
transition_state_element.paint_order);
element_data->visual_overflow_rect_in_layout_space =
PhysicalRect::EnclosingRect(
transition_state_element.overflow_rect_in_layout_space);
element_data->captured_rect_in_layout_space =
transition_state_element.captured_rect_in_layout_space;
CHECK_LE(transition_state_element.container_writing_mode,
static_cast<uint8_t>(WritingMode::kMaxWritingMode));
element_data->container_writing_mode = static_cast<WritingMode>(
transition_state_element.container_writing_mode);
element_data->CacheGeometryState();
element_data_map_.insert(name, std::move(element_data));
}
// The aim of this flag is to serialize/deserialize SPA state using MPA
// machinery. The intent is to use SPA tests to test MPA implementation as
// well. To that end, if the flag is enabled we should invalidate styles and
// clear the view transition names, because the "true" MPA implementation
// would not have any style or names set.
if (RuntimeEnabledFeatures::SerializeViewTransitionStateInSPAEnabled()) {
InvalidateHitTestingCache();
InvalidateStyle();
document_->GetStyleEngine().SetViewTransitionNames({});
}
}
ViewTransitionStyleTracker::~ViewTransitionStyleTracker() {
if (!RuntimeEnabledFeatures::SerializeViewTransitionStateInSPAEnabled()) {
CHECK_EQ(state_, State::kFinished);
}
}
void ViewTransitionStyleTracker::AddConsoleError(
String message,
Vector<DOMNodeId> related_nodes) {
auto* console_message = MakeGarbageCollected<ConsoleMessage>(
mojom::blink::ConsoleMessageSource::kRendering,
mojom::blink::ConsoleMessageLevel::kError, std::move(message));
console_message->SetNodes(document_->GetFrame(), std::move(related_nodes));
document_->AddConsoleMessage(console_message);
}
void ViewTransitionStyleTracker::AddTransitionElement(
Element* element,
const AtomicString& name) {
DCHECK(element);
// Insert an empty hash set for the element if it doesn't exist, or get it if
// it does.
auto& value = pending_transition_element_names_
.insert(element, HashSet<std::pair<AtomicString, int>>())
.stored_value->value;
// Find the existing name if one is there. If it is there, do nothing.
if (base::Contains(value, name, &std::pair<AtomicString, int>::first))
return;
// Otherwise, insert a new sequence id with this name. We'll use the sequence
// to sort later.
value.insert(std::make_pair(name, set_element_sequence_id_));
++set_element_sequence_id_;
}
bool ViewTransitionStyleTracker::MatchForOnlyChild(
PseudoId pseudo_id,
const AtomicString& view_transition_name) const {
switch (pseudo_id) {
case kPseudoIdViewTransition:
DCHECK(!view_transition_name);
return false;
case kPseudoIdViewTransitionGroup: {
DCHECK(view_transition_name);
DCHECK(element_data_map_.Contains(view_transition_name));
return element_data_map_.size() == 1;
}
case kPseudoIdViewTransitionImagePair:
DCHECK(view_transition_name);
return true;
case kPseudoIdViewTransitionOld: {
DCHECK(view_transition_name);
auto it = element_data_map_.find(view_transition_name);
DCHECK(it != element_data_map_.end());
const auto& element_data = it->value;
return !element_data->new_snapshot_id.IsValid();
}
case kPseudoIdViewTransitionNew: {
DCHECK(view_transition_name);
auto it = element_data_map_.find(view_transition_name);
DCHECK(it != element_data_map_.end());
const auto& element_data = it->value;
return !element_data->old_snapshot_id.IsValid();
}
default:
NOTREACHED();
}
return false;
}
void ViewTransitionStyleTracker::AddTransitionElementsFromCSS() {
DCHECK(document_ && document_->View());
// We need our paint layers, and z-order lists which is done during
// compositing inputs update.
DCHECK_GE(document_->Lifecycle().GetState(),
DocumentLifecycle::kCompositingInputsClean);
AddTransitionElementsFromCSSRecursive(
document_->GetLayoutView()->PaintingLayer());
}
void ViewTransitionStyleTracker::AddTransitionElementsFromCSSRecursive(
PaintLayer* root) {
// We want to call AddTransitionElements in the order in which
// PaintLayerPaintOrderIterator would cause us to paint the elements.
// Specifically, parents are added before their children, and lower z-index
// children are added before higher z-index children. Given that, what we
// need to do is to first add `root`'s element, and then recurse using the
// PaintLayerPaintOrderIterator which will return values in the correct
// z-index order.
//
// Note that the order of calls to AddTransitionElement determines the DOM
// order of pseudo-elements constructed to represent the transition elements,
// which by default will also represent the paint order of the pseudo-elements
// (unless changed by something like z-index on the pseudo-elements).
auto& root_object = root->GetLayoutObject();
auto& root_style = root_object.StyleRef();
if (root_style.ViewTransitionName() && !root_object.IsFragmented()) {
DCHECK(root_object.GetNode());
DCHECK(root_object.GetNode()->IsElementNode());
AddTransitionElement(DynamicTo<Element>(root_object.GetNode()),
root_style.ViewTransitionName());
}
if (root_object.ChildPaintBlockedByDisplayLock())
return;
PaintLayerPaintOrderIterator child_iterator(root, kAllChildren);
while (auto* child = child_iterator.Next()) {
AddTransitionElementsFromCSSRecursive(child);
}
}
bool ViewTransitionStyleTracker::FlattenAndVerifyElements(
VectorOf<Element>& elements,
VectorOf<AtomicString>& transition_names) {
// Fail if the document element does not exist, since that's the place where
// we attach pseudo elements, and if it's not there, we can't do a transition.
if (!document_->documentElement()) {
return false;
}
// If the root element exists but doesn't generate a layout object then there
// can't be any elements participating in the transition since no element can
// generate a box. This is a valid state for things like entry or exit
// animations.
if (!document_->documentElement()->GetLayoutObject()) {
return true;
}
// We need to flatten the data first, and sort it by ordering which reflects
// the setElement ordering.
struct FlatData : public GarbageCollected<FlatData> {
FlatData(Element* element, const AtomicString& name, int ordering)
: element(element), name(name), ordering(ordering) {}
Member<Element> element;
AtomicString name;
int ordering;
void Trace(Visitor* visitor) const { visitor->Trace(element); }
};
VectorOf<FlatData> flat_list;
// Flatten it.
for (auto& [element, names] : pending_transition_element_names_) {
DCHECK(element->GetLayoutObject());
// TODO(khushalsagar): Simplify this, we don't support multiple
// view-transition-names per element.
for (auto& name_pair : names) {
flat_list.push_back(MakeGarbageCollected<FlatData>(
element, name_pair.first, name_pair.second));
}
}
// Sort it.
std::sort(flat_list.begin(), flat_list.end(),
[](const FlatData* a, const FlatData* b) {
return a->ordering < b->ordering;
});
// Verify it.
for (auto& flat_data : flat_list) {
auto& name = flat_data->name;
auto& element = flat_data->element;
if (UNLIKELY(transition_names.Contains(name))) {
StringBuilder message;
message.Append(kDuplicateTagBaseError);
message.Append(name);
AddConsoleError(message.ReleaseString());
return false;
}
transition_names.push_back(name);
elements.push_back(element);
}
return true;
}
bool ViewTransitionStyleTracker::Capture() {
DCHECK_EQ(state_, State::kIdle);
// Flatten `pending_transition_element_names_` into a vector of names and
// elements. This process also verifies that the name-element combinations are
// valid.
VectorOf<AtomicString> transition_names;
VectorOf<Element> elements;
bool success = FlattenAndVerifyElements(elements, transition_names);
if (!success)
return false;
// Now we know that we can start a transition. Update the state and populate
// `element_data_map_`.
state_ = State::kCapturing;
InvalidateHitTestingCache();
captured_name_count_ = transition_names.size();
element_data_map_.ReserveCapacityForSize(captured_name_count_);
HeapHashMap<Member<Element>, viz::ViewTransitionElementResourceId>
element_snapshot_ids;
int next_index = 0;
for (int i = 0; i < captured_name_count_; ++i) {
const auto& name = transition_names[i];
const auto& element = elements[i];
// Reuse any previously generated snapshot_id for this element. If there was
// none yet, then generate the resource id.
auto& snapshot_id =
element_snapshot_ids
.insert(element, viz::ViewTransitionElementResourceId())
.stored_value->value;
if (!snapshot_id.IsValid()) {
snapshot_id = viz::ViewTransitionElementResourceId::Generate();
capture_resource_ids_.push_back(snapshot_id);
}
auto* element_data = MakeGarbageCollected<ElementData>();
element_data->target_element = element;
element_data->element_index = next_index++;
element_data->old_snapshot_id = snapshot_id;
element_data_map_.insert(name, std::move(element_data));
if (element->IsDocumentElement()) {
is_root_transitioning_ = true;
}
}
#if DCHECK_IS_ON()
for (wtf_size_t i = 0; i < transition_names.size(); ++i) {
DCHECK_EQ(transition_names.Find(transition_names[i]), i)
<< " Duplicate transition name: " << transition_names[i];
}
#endif
// This informs the style engine the set of names we have, which will be used
// to create the pseudo element tree.
document_->GetStyleEngine().SetViewTransitionNames(transition_names);
// We need a style invalidation to generate the pseudo element tree.
InvalidateStyle();
set_element_sequence_id_ = 0;
pending_transition_element_names_.clear();
DCHECK(!snapshot_root_size_at_capture_.has_value());
snapshot_root_size_at_capture_ = GetSnapshotRootSize();
return true;
}
void ViewTransitionStyleTracker::CaptureResolved() {
DCHECK_EQ(state_, State::kCapturing);
state_ = State::kCaptured;
// TODO(crbug.com/1347473): We should also suppress hit testing at this point,
// since we're about to start painting the element as a captured snapshot, but
// we still haven't given script chance to modify the DOM to the new state.
InvalidateHitTestingCache();
// Since the elements will be unset, we need to invalidate their style first.
// TODO(vmpstr): We don't have to invalidate the pseudo styles at this point,
// just the transition elements. We can split InvalidateStyle() into two
// functions as an optimization.
InvalidateStyle();
for (auto& entry : element_data_map_) {
auto& element_data = entry.value;
element_data->target_element = nullptr;
element_data->effect_node = nullptr;
}
root_effect_node_ = nullptr;
is_root_transitioning_ = false;
}
VectorOf<Element> ViewTransitionStyleTracker::GetTransitioningElements() const {
// In stable states, we don't have transitioning elements.
if (state_ == State::kIdle || state_ == State::kCaptured)
return {};
VectorOf<Element> result;
for (auto& entry : element_data_map_) {
if (entry.value->target_element &&
!entry.value->target_element->IsDocumentElement()) {
result.push_back(entry.value->target_element);
}
}
return result;
}
bool ViewTransitionStyleTracker::Start() {
DCHECK_EQ(state_, State::kCaptured);
// Flatten `pending_transition_element_names_` into a vector of names and
// elements. This process also verifies that the name-element combinations are
// valid.
VectorOf<AtomicString> transition_names;
VectorOf<Element> elements;
bool success = FlattenAndVerifyElements(elements, transition_names);
if (!success)
return false;
state_ = State::kStarted;
InvalidateHitTestingCache();
HeapHashMap<Member<Element>, viz::ViewTransitionElementResourceId>
element_snapshot_ids;
bool found_new_names = false;
// If this tracker was created from serialized state, transition tags are
// initialized with the style system in the start phase.
if (deserialized_) {
DCHECK(document_->GetStyleEngine().ViewTransitionTags().empty());
found_new_names = true;
}
// We would have an new element index for each of the element_data_map_
// entries.
int next_index = element_data_map_.size();
for (wtf_size_t i = 0; i < elements.size(); ++i) {
const auto& name = transition_names[i];
const auto& element = elements[i];
// Insert a new name data if there is no data for this name yet.
if (!element_data_map_.Contains(name)) {
found_new_names = true;
auto* data = MakeGarbageCollected<ElementData>();
data->element_index = next_index++;
element_data_map_.insert(name, data);
}
// Reuse any previously generated snapshot_id for this element. If there was
// none yet, then generate the resource id.
auto& snapshot_id =
element_snapshot_ids
.insert(element, viz::ViewTransitionElementResourceId())
.stored_value->value;
if (!snapshot_id.IsValid())
snapshot_id = viz::ViewTransitionElementResourceId::Generate();
auto& element_data = element_data_map_.find(name)->value;
DCHECK(!element_data->target_element);
element_data->target_element = element;
element_data->new_snapshot_id = snapshot_id;
// Verify that the element_index assigned in Capture is less than next_index
// here, just as a sanity check.
DCHECK_LT(element_data->element_index, next_index);
if (element->IsDocumentElement()) {
is_root_transitioning_ = true;
}
}
if (found_new_names) {
VectorOf<std::pair<AtomicString, int>> new_name_pairs;
for (auto& [name, data] : element_data_map_) {
new_name_pairs.push_back(std::make_pair(name, data->element_index));
}
std::sort(new_name_pairs.begin(), new_name_pairs.end(),
[](const std::pair<AtomicString, int>& left,
const std::pair<AtomicString, int>& right) {
return left.second < right.second;
});
#if DCHECK_IS_ON()
int last_index = -1;
#endif
VectorOf<AtomicString> new_names;
for (auto& [name, index] : new_name_pairs) {
new_names.push_back(name);
#if DCHECK_IS_ON()
DCHECK_NE(last_index, index);
last_index = index;
#endif
}
#if DCHECK_IS_ON()
for (wtf_size_t i = 0; i < new_names.size(); ++i) {
DCHECK_EQ(new_names.Find(new_names[i]), i)
<< " Duplicate transition name: " << new_names[i];
}
#endif
document_->GetStyleEngine().SetViewTransitionNames(new_names);
}
DCHECK_GE(document_->Lifecycle().GetState(),
DocumentLifecycle::kPrePaintClean);
// We need a style invalidation to generate new content pseudo elements for
// new elements in the DOM.
InvalidateStyle();
if (auto* page = document_->GetPage())
page->Animator().SetHasViewTransition(true);
return true;
}
void ViewTransitionStyleTracker::StartFinished() {
DCHECK_EQ(state_, State::kStarted);
EndTransition();
}
void ViewTransitionStyleTracker::Abort() {
EndTransition();
}
void ViewTransitionStyleTracker::EndTransition() {
CHECK_NE(state_, State::kFinished);
state_ = State::kFinished;
InvalidateHitTestingCache();
// We need a style invalidation to remove the pseudo element tree. This needs
// to be done before we clear the data, since we need to invalidate the
// transition elements stored in `element_data_map_`.
InvalidateStyle();
element_data_map_.clear();
pending_transition_element_names_.clear();
set_element_sequence_id_ = 0;
document_->GetStyleEngine().SetViewTransitionNames({});
is_root_transitioning_ = false;
if (auto* page = document_->GetPage())
page->Animator().SetHasViewTransition(false);
}
void ViewTransitionStyleTracker::UpdateElementIndicesAndSnapshotId(
Element* element,
ViewTransitionElementId& index,
viz::ViewTransitionElementResourceId& resource_id) const {
DCHECK(element);
for (const auto& entry : element_data_map_) {
if (entry.value->target_element == element) {
index.AddIndex(entry.value->element_index);
const auto& snapshot_id = HasLiveNewContent()
? entry.value->new_snapshot_id
: entry.value->old_snapshot_id;
DCHECK(!resource_id.IsValid() || resource_id == snapshot_id);
if (!resource_id.IsValid())
resource_id = snapshot_id;
}
}
DCHECK(resource_id.IsValid());
}
PseudoElement* ViewTransitionStyleTracker::CreatePseudoElement(
Element* parent,
PseudoId pseudo_id,
const AtomicString& view_transition_name) {
DCHECK(IsTransitionPseudoElement(pseudo_id));
DCHECK(pseudo_id == kPseudoIdViewTransition || view_transition_name);
switch (pseudo_id) {
case kPseudoIdViewTransition:
case kPseudoIdViewTransitionGroup:
return MakeGarbageCollected<ViewTransitionPseudoElementBase>(
parent, pseudo_id, view_transition_name, this);
case kPseudoIdViewTransitionImagePair:
return MakeGarbageCollected<ImageWrapperPseudoElement>(
parent, pseudo_id, view_transition_name, this);
case kPseudoIdViewTransitionOld: {
DCHECK(view_transition_name);
const auto& element_data =
element_data_map_.find(view_transition_name)->value;
// If live data is tracking new elements then use the cached data for
// the pseudo element displaying snapshot of old element.
bool use_cached_data = HasLiveNewContent();
auto captured_rect = element_data->GetCapturedSubrect(use_cached_data);
auto border_box_rect =
element_data->GetBorderBoxRect(use_cached_data, device_pixel_ratio_);
auto snapshot_id = element_data->old_snapshot_id;
// Note that we say that this layer is not a live content
// layer, even though it may currently be displaying live contents. The
// reason is that we want to avoid updating this value later, which
// involves propagating the update all the way to cc. However, this means
// that we have to have the save directive come in the same frame as the
// first frame that displays this content. Otherwise, we risk DCHECK. This
// is currently the behavior as specced, but this is subtle.
// TODO(vmpstr): Maybe we should just use HasLiveNewContent() here, and
// update it when the value changes.
auto* pseudo_element = MakeGarbageCollected<ViewTransitionContentElement>(
parent, pseudo_id, view_transition_name, snapshot_id,
/*is_live_content_element=*/false, this);
pseudo_element->SetIntrinsicSize(captured_rect, border_box_rect);
return pseudo_element;
}
case kPseudoIdViewTransitionNew: {
DCHECK(view_transition_name);
const auto& element_data =
element_data_map_.find(view_transition_name)->value;
bool use_cached_data = false;
auto captured_rect = element_data->GetCapturedSubrect(use_cached_data);
auto border_box_rect =
element_data->GetBorderBoxRect(use_cached_data, device_pixel_ratio_);
auto snapshot_id = element_data->new_snapshot_id;
auto* pseudo_element = MakeGarbageCollected<ViewTransitionContentElement>(
parent, pseudo_id, view_transition_name, snapshot_id,
/*is_live_content_element=*/true, this);
pseudo_element->SetIntrinsicSize(captured_rect, border_box_rect);
return pseudo_element;
}
default:
NOTREACHED();
}
return nullptr;
}
bool ViewTransitionStyleTracker::RunPostPrePaintSteps() {
DCHECK_GE(document_->Lifecycle().GetState(),
DocumentLifecycle::kPrePaintClean);
// Abort if the document element is not there.
if (!document_->documentElement()) {
return false;
}
if (!document_->documentElement()->GetLayoutObject()) {
// If we have any view transition elements, while having no
// documentElement->GetLayoutObject(), we should abort. Target elements are
// only set on the current phase of the animation, so it means that the
// documentElement's layout object disappeared in this phase.
for (auto& entry : element_data_map_) {
auto& element_data = entry.value;
if (element_data->target_element) {
return false;
}
}
return true;
}
DCHECK(document_->documentElement() &&
document_->documentElement()->GetLayoutObject());
// We don't support changing device pixel ratio, because it's uncommon and
// textures may have already been captured at a different size.
if (device_pixel_ratio_ != DevicePixelRatioFromDocument(*document_)) {
return false;
}
if (SnapshotRootDidChangeSize()) {
return false;
}
const int max_capture_size = ComputeMaxCaptureSize(
document_->GetPage()->GetChromeClient().GetMaxRenderBufferBounds(
*document_->GetFrame()),
*snapshot_root_size_at_capture_);
bool needs_style_invalidation = false;
for (auto& entry : element_data_map_) {
auto& element_data = entry.value;
if (!element_data->target_element)
continue;
DCHECK(document_->documentElement());
auto* layout_object = element_data->target_element->GetLayoutObject();
if (!layout_object) {
return false;
}
// End the transition if any of the objects have become fragmented.
if (layout_object->IsFragmented()) {
return false;
}
ContainerProperties container_properties;
PhysicalRect visual_overflow_rect_in_layout_space;
WritingMode writing_mode;
absl::optional<gfx::RectF> captured_rect_in_layout_space;
if (element_data->target_element->IsDocumentElement()) {
auto layout_view_size = PhysicalSize(GetSnapshotRootSize());
auto layout_view_size_in_css_space = layout_view_size;
layout_view_size_in_css_space.Scale(1 / device_pixel_ratio_);
container_properties =
ContainerProperties(layout_view_size_in_css_space, gfx::Transform());
visual_overflow_rect_in_layout_space.size = layout_view_size;
writing_mode = layout_object->StyleRef().GetWritingMode();
} else {
ComputeLiveElementGeometry(max_capture_size, *layout_object,
container_properties,
visual_overflow_rect_in_layout_space,
writing_mode, captured_rect_in_layout_space);
}
if (!element_data->container_properties.empty() &&
element_data->container_properties.back() == container_properties &&
visual_overflow_rect_in_layout_space ==
element_data->visual_overflow_rect_in_layout_space &&