-
Notifications
You must be signed in to change notification settings - Fork 535
Expand file tree
/
Copy pathlayout_context.cc
More file actions
1362 lines (1223 loc) · 46.4 KB
/
Copy pathlayout_context.cc
File metadata and controls
1362 lines (1223 loc) · 46.4 KB
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 2019 The Lynx Authors. All rights reserved.
// Licensed under the Apache License Version 2.0 that can be found in the
// LICENSE file in the root directory of this source tree.
#include "core/renderer/ui_wrapper/layout/layout_context.h"
#include <algorithm>
#include <chrono>
#include <cmath>
#include <sstream>
#include <string>
#include <utility>
#include <vector>
#include "base/include/fml/synchronization/waitable_event.h"
#include "base/include/log/logging.h"
#include "base/include/no_destructor.h"
#include "base/include/value/table.h"
#include "base/trace/native/trace_event.h"
#include "core/build/gen/lynx_sub_error_code.h"
#include "core/public/layout_node_value.h"
#include "core/renderer/dom/attribute_holder.h"
#include "core/renderer/dom/element_manager.h"
#include "core/renderer/lynx_env_config.h"
#include "core/renderer/starlight/layout/box_info.h"
#include "core/renderer/starlight/layout/layout_global.h"
#include "core/renderer/starlight/style/css_type.h"
#include "core/renderer/starlight/style/default_layout_style.h"
#include "core/renderer/starlight/types/layout_constraints.h"
#include "core/renderer/starlight/types/layout_directions.h"
#include "core/renderer/starlight/types/nlength.h"
#include "core/renderer/trace/renderer_trace_event_def.h"
#include "core/renderer/ui_wrapper/layout/layout_context_data.h"
#include "core/renderer/ui_wrapper/layout/no_needed_layout_list.h"
#include "core/renderer/utils/lynx_env.h"
#include "core/runtime/lepus/json_parser.h"
#include "core/services/feature_count/feature_counter.h"
#include "core/services/long_task_timing/long_task_monitor.h"
#include "core/services/recorder/recorder_controller.h"
#include "core/services/timing_handler/timing_constants.h"
namespace lynx {
namespace tasm {
namespace {
void CollectDirtyNodeForList(LayoutNode* node,
const std::shared_ptr<PipelineOptions>& options) {
static bool enable_native_list_nested =
LynxEnv::GetInstance().EnableNativeListNested();
if ((!enable_native_list_nested && options->operation_id == 0) ||
(enable_native_list_nested && node->id() != options->list_id_)) {
// Note: We should avoid adding the parent list node to
// options->updated_list_elements_ when rendering a list item.
options->updated_list_elements_.emplace_back(node->id());
}
}
} // namespace
LayoutContext::LayoutContext(
std::unique_ptr<Delegate> delegate,
std::unique_ptr<LayoutCtxPlatformImpl> platform_impl,
const LynxEnvConfig& lynx_env_config, const PageOptions& page_options)
: platform_impl_(std::move(platform_impl)),
delegate_(std::move(delegate)),
root_(nullptr),
viewport_(),
init_css_style_(std::make_unique<starlight::ComputedCSSStyle>(
lynx_env_config.LayoutsUnitPerPx(),
lynx_env_config.PhysicalPixelsPerLayoutUnit())),
lynx_env_config_(lynx_env_config),
page_options_(page_options) {
// TODO(chennengshi), add test for lynx_shell_builder_unittest, then the
// condition can be deleted.
if (platform_impl_) {
platform_impl_->SetLayoutNodeManager(this);
}
}
LayoutContext::~LayoutContext() {
if (platform_impl_ != nullptr) {
DestroyPlatformNodesIfNeeded();
platform_impl_->Destroy();
}
SetRootInner(nullptr);
}
void LayoutContext::SetMeasureFunc(int32_t id,
std::unique_ptr<MeasureFunc> measure_func) {
auto node = FindNodeById(id);
if (node == nullptr) {
return;
}
node->SetMeasureFunc(std::move(measure_func));
}
void LayoutContext::MarkDirtyAndRequestLayout(int32_t id) {
auto node = FindNodeById(id);
if (node == nullptr) {
return;
}
node->MarkDirtyAndRequestLayout();
}
void LayoutContext::MarkDirtyAndForceLayout(int32_t id) {
auto node = FindNodeById(id);
if (node == nullptr) {
return;
}
node->slnode()->MarkDirtyAndRequestLayout(true);
}
bool LayoutContext::IsDirty(int32_t id) {
auto node = FindNodeById(id);
if (node == nullptr) {
return false;
}
return node->IsDirty();
}
FlexDirection LayoutContext::GetFlexDirection(int32_t id) {
auto node = FindNodeById(id);
starlight::FlexDirectionType result =
node ? node->slnode()->GetCSSMutableStyle()->GetFlexDirection()
: starlight::FlexDirectionType::kColumn;
return static_cast<FlexDirection>(result);
}
float LayoutContext::GetWidth(int32_t id) {
auto node = FindNodeById(id);
if (node == nullptr) {
return 0.0f;
}
// FIXME(liting): vw vh percentage
auto width = starlight::NLengthToFakeLayoutUnit(
node->slnode()->GetCSSStyle()->GetWidth());
return width.ClampIndefiniteToZero().ToFloat();
}
float LayoutContext::GetHeight(int32_t id) {
auto node = FindNodeById(id);
if (node == nullptr) {
return 0.0f;
}
// FIXME(liting): vw vh percentage
auto height = lynx::starlight::NLengthToFakeLayoutUnit(
node->slnode()->GetCSSStyle()->GetHeight());
return height.ClampIndefiniteToZero().ToFloat();
}
float LayoutContext::GetPaddingLeft(int32_t id) {
auto node = FindNodeById(id);
if (node == nullptr) {
return 0.0f;
}
const auto& style = node->slnode()->GetCSSStyle();
return starlight::NLengthToFakeLayoutUnit(style->GetPaddingLeft())
.ClampIndefiniteToZero()
.ToFloat();
}
float LayoutContext::GetPaddingTop(int32_t id) {
auto node = FindNodeById(id);
if (node == nullptr) {
return 0.0f;
}
const auto& style = node->slnode()->GetCSSStyle();
return starlight::NLengthToFakeLayoutUnit(style->GetPaddingTop())
.ClampIndefiniteToZero()
.ToFloat();
}
float LayoutContext::GetPaddingRight(int32_t id) {
auto node = FindNodeById(id);
if (node == nullptr) {
return 0.0f;
}
const auto& style = node->slnode()->GetCSSStyle();
return starlight::NLengthToFakeLayoutUnit(style->GetPaddingRight())
.ClampIndefiniteToZero()
.ToFloat();
}
float LayoutContext::GetPaddingBottom(int32_t id) {
auto node = FindNodeById(id);
if (node == nullptr) {
return 0.0f;
}
const auto& style = node->slnode()->GetCSSStyle();
return starlight::NLengthToFakeLayoutUnit(style->GetPaddingBottom())
.ClampIndefiniteToZero()
.ToFloat();
}
float LayoutContext::GetMarginLeft(int32_t id) {
auto node = FindNodeById(id);
if (node == nullptr) {
return 0.0f;
}
const auto& style = node->slnode()->GetCSSStyle();
return starlight::NLengthToFakeLayoutUnit(style->GetMarginLeft())
.ClampIndefiniteToZero()
.ToFloat();
}
float LayoutContext::GetMarginTop(int32_t id) {
auto node = FindNodeById(id);
if (node == nullptr) {
return 0.0f;
}
const auto& style = node->slnode()->GetCSSStyle();
return starlight::NLengthToFakeLayoutUnit(style->GetMarginTop())
.ClampIndefiniteToZero()
.ToFloat();
}
float LayoutContext::GetMarginRight(int32_t id) {
auto node = FindNodeById(id);
if (node == nullptr) {
return 0.0f;
}
const auto& style = node->slnode()->GetCSSStyle();
return starlight::NLengthToFakeLayoutUnit(style->GetMarginRight())
.ClampIndefiniteToZero()
.ToFloat();
}
float LayoutContext::GetMarginBottom(int32_t id) {
auto node = FindNodeById(id);
if (node == nullptr) {
return 0.0f;
}
const auto& style = node->slnode()->GetCSSStyle();
return starlight::NLengthToFakeLayoutUnit(style->GetMarginBottom())
.ClampIndefiniteToZero()
.ToFloat();
}
float LayoutContext::GetMinWidth(int32_t id) {
auto node = FindNodeById(id);
if (node == nullptr) {
return LayoutNodeStyle::UNDEFINED_MIN_SIZE;
}
const auto& style = node->slnode()->GetCSSStyle();
return starlight::NLengthToFakeLayoutUnit(style->GetMinWidth())
.ClampIndefiniteToZero()
.ToFloat();
}
float LayoutContext::GetMaxWidth(int32_t id) {
auto node = FindNodeById(id);
if (node == nullptr) {
return LayoutNodeStyle::UNDEFINED_MAX_SIZE;
}
const auto& style = node->slnode()->GetCSSStyle();
return starlight::NLengthToFakeLayoutUnit(style->GetMaxWidth())
.ClampIndefiniteToZero()
.ToFloat();
}
float LayoutContext::GetMinHeight(int32_t id) {
auto node = FindNodeById(id);
if (node == nullptr) {
return LayoutNodeStyle::UNDEFINED_MIN_SIZE;
}
const auto& style = node->slnode()->GetCSSStyle();
return starlight::NLengthToFakeLayoutUnit(style->GetMinHeight())
.ClampIndefiniteToZero()
.ToFloat();
}
float LayoutContext::GetMaxHeight(int32_t id) {
auto node = FindNodeById(id);
if (node == nullptr) {
return LayoutNodeStyle::UNDEFINED_MAX_SIZE;
}
const auto& style = node->slnode()->GetCSSStyle();
return starlight::NLengthToFakeLayoutUnit(style->GetMaxHeight())
.ClampIndefiniteToZero()
.ToFloat();
}
LayoutResult LayoutContext::UpdateMeasureByPlatform(int32_t id, float width,
int width_mode,
float height,
int height_mode,
bool final_measure) {
auto node = FindNodeById(id);
if (node == nullptr) {
return LayoutResult{0, 0};
}
starlight::Constraints constraints;
constraints[starlight::kHorizontal] = starlight::OneSideConstraint(
width, static_cast<SLMeasureMode>(width_mode));
constraints[starlight::kVertical] = starlight::OneSideConstraint(
height, static_cast<SLMeasureMode>(height_mode));
FloatSize result = node->UpdateMeasureByPlatform(constraints, final_measure);
return LayoutResult{result.width_, result.height_, result.baseline_};
}
void LayoutContext::AlignmentByPlatform(int32_t id, float offset_top,
float offset_left) {
auto node = FindNodeById(id);
if (node == nullptr) {
return;
}
node->AlignmentByPlatform(offset_top, offset_left);
}
void LayoutContext::UpdateLayoutNodeProps(
int32_t id, const fml::RefPtr<PropBundle>& props) {
auto node = FindNodeById(id);
UpdateLayoutNodePropsInner(node, props);
}
void LayoutContext::UpdateLayoutNodePropsInner(
LayoutNode* node, const fml::RefPtr<PropBundle>& props) {
if (node->is_common() && !node->is_inline_view()) {
return;
}
platform_impl_->UpdateLayoutNode(node->id(), props.get());
}
void LayoutContext::UpdateLayoutNodeFontSize(int32_t id,
double cur_node_font_size,
double root_node_font_size,
double font_scale) {
auto node = FindNodeById(id);
UpdateLayoutNodeFontSizeInner(node, cur_node_font_size, root_node_font_size,
font_scale);
}
void LayoutContext::UpdateLayoutNodeFontSizeInner(LayoutNode* node,
double cur_node_font_size,
double root_node_font_size,
double font_scale) {
node->ConsumeFontSize(cur_node_font_size, root_node_font_size, font_scale);
}
void LayoutContext::UpdateLayoutNodeStyle(int32_t id, CSSPropertyID css_id,
const tasm::CSSValue& value) {
auto node = FindNodeById(id);
if (node == nullptr || node->slnode() == nullptr) {
LOGE("[LayoutContext] UpdateLayoutNodeStyle for null, id :"
<< id << " css_id: " << css_id << " value: " << value.AsJsonString());
LYNX_ERROR(error::E_LAYOUT_INTERNAL, "FindNodeById is null",
"This error is caught by native, please ask Lynx for help");
base::ErrorStorage::GetInstance().AddCustomInfoToError("id",
std::to_string(id));
}
UpdateLayoutNodeStyleInner(node, css_id, value);
}
void LayoutContext::UpdateLayoutNodeStyleInner(LayoutNode* node,
lynx::tasm::CSSPropertyID css_id,
const tasm::CSSValue& value) {
node->ConsumeStyle(css_id, value);
if (node->slnode()->GetEnableFixedNew()) {
CheckFixed(node);
}
}
void LayoutContext::ResetLayoutNodeStyle(int32_t id, CSSPropertyID css_id) {
auto node = FindNodeById(id);
ResetLayoutNodeStyleInner(node, css_id);
}
void LayoutContext::ResetLayoutNodeStyleInner(
LayoutNode* node, lynx::tasm::CSSPropertyID css_id) {
node->ConsumeStyle(css_id, CSSValue(), true);
if (node->slnode()->GetEnableFixedNew()) {
CheckFixed(node);
}
}
void LayoutContext::UpdateLayoutNodeAttribute(int32_t id,
starlight::LayoutAttribute key,
const lepus::Value& value) {
auto node = FindNodeById(id);
UpdateLayoutNodeAttributeInner(node, key, value);
}
void LayoutContext::UpdateLayoutNodeAttributeInner(
LayoutNode* node, starlight::LayoutAttribute key,
const lepus::Value& value) {
node->ConsumeAttribute(key, value);
}
void LayoutContext::ResetLayoutNodeAttribute(int32_t id,
starlight::LayoutAttribute key) {
auto node = FindNodeById(id);
node->ConsumeAttribute(key, lepus::Value(), true);
}
void LayoutContext::UpdateLayoutNodeByBundle(
int32_t id, std::unique_ptr<LayoutBundle> bundle) {
auto target_node = bundle->is_create_bundle
? InitLayoutNodeWithBundle(id, bundle.get())
: FindNodeById(id);
if (!target_node) {
LOGE("[LayoutContext] UpdateLayoutNodeByBundle for null node, id :" << id);
return;
}
if (bundle->cur_node_font_size >= 0 && bundle->root_node_font_size >= 0) {
UpdateLayoutNodeFontSizeInner(target_node, bundle->cur_node_font_size,
bundle->root_node_font_size,
bundle->font_scale);
}
for (const auto& reset_id : bundle->reset_styles) {
ResetLayoutNodeStyleInner(target_node, reset_id);
}
for (const auto& pair : bundle->styles) {
UpdateLayoutNodeStyleInner(target_node, pair.first, pair.second);
}
for (const auto& pair : bundle->attrs) {
UpdateLayoutNodeAttributeInner(target_node, pair.first, pair.second);
}
if (bundle->is_create_bundle) {
return;
}
for (const auto& prop_bundle : bundle->update_prop_bundles) {
UpdateLayoutNodePropsInner(target_node, prop_bundle);
}
if (bundle->is_dirty) {
target_node->MarkDirty();
}
}
LayoutNode* LayoutContext::InitLayoutNodeWithBundle(int32_t id,
LayoutBundle* bundle) {
auto target_node = CreateLayoutNode(id, bundle->tag);
if (bundle->is_root) {
SetRootInner(target_node);
}
AttachLayoutNodeTypeInner(target_node, bundle->tag, bundle->allow_inline,
bundle->shadownode_prop_bundle);
return target_node;
}
LayoutNode* LayoutContext::CreateLayoutNode(int32_t id,
const base::String& tag) {
LayoutNode* layout_node =
&layout_nodes_
.emplace(std::piecewise_construct, std::forward_as_tuple(id),
std::forward_as_tuple(id, layout_configs_, lynx_env_config_,
*init_css_style_))
.first->second;
layout_node->SetTag(tag);
if (tag.str() == kListNodeTag) {
layout_node->slnode()->MarkList();
}
if ((layout_configs_.enable_fixed_new_ ||
layout_configs_.enable_unify_fixed_behavior_) &&
root_) {
layout_node->slnode()->SetRoot(root_->slnode());
}
layout_node->slnode()->SetEventHandler(this);
if (hierarchy_observer_) {
hierarchy_observer_->OnLayoutObjectCreated(id, layout_node->slnode());
}
return layout_node;
}
void LayoutContext::InsertLayoutNode(int32_t parent_id, int32_t child_id,
int index) {
auto parent = FindNodeById(parent_id);
auto child = FindNodeById(child_id);
parent->InsertNode(child, index);
if (!parent->is_common() &&
(!child->is_common() || child->is_inline_view())) {
platform_impl_->InsertLayoutNode(parent->id(), child->id(), index);
}
}
void LayoutContext::RemoveLayoutNodeAtIndex(int32_t parent_id, int index) {
auto parent = FindNodeById(parent_id);
auto child = parent->RemoveNodeAtIndex(index);
if (child == nullptr) return;
if (child->slnode()->IsNewFixed()) {
UpdateFixedNodeSet(child, false);
}
if (parent && !parent->is_common()) {
platform_impl_->RemoveLayoutNode(parent->id(), child->id(), index);
}
}
void LayoutContext::InsertLayoutNodeBefore(int32_t parent_id, int32_t child_id,
int32_t ref_id) {
auto parent = FindNodeById(parent_id);
auto ref_node = FindNodeById(ref_id);
int index = 0;
if (ref_node == nullptr) {
// null ref node indicates to append the child to the end
index = static_cast<int>(parent->children().size());
} else {
index = GetIndexForChild(parent, ref_node);
if (index < 0) {
LOGE("LayoutContext::InsertLayoutNodeBefore can not find child!!");
return;
}
}
InsertLayoutNode(parent_id, child_id, index);
}
void LayoutContext::RemoveLayoutNode(int32_t parent_id, int32_t child_id) {
auto parent = FindNodeById(parent_id);
auto child = FindNodeById(child_id);
int index = GetIndexForChild(parent, child);
if (index < 0) {
LOGE("LayoutContext::RemoveLayoutNode can not find child!!");
return;
}
RemoveLayoutNodeAtIndex(parent_id, index);
}
void LayoutContext::DestroyLayoutNode(int32_t id) {
auto node = FindNodeById(id);
if (node != nullptr) {
UnlinkNodeFromChildren(node);
UnlinkNodeFromParent(node);
bool has_platform_shadownode = !node->is_common() || node->is_inline_view();
if (has_platform_shadownode) {
destroyed_platform_nodes_.insert(id);
}
if (node == root_) {
// The root node will be destroyed, so we need to set root_ to nullptr
// to avoid accessing destroyed root node.
root_ = nullptr;
}
layout_nodes_.erase(id);
}
}
void LayoutContext::UnlinkNodeFromParent(LayoutNode* node) {
if (node == nullptr) return;
auto parent = node->parent();
if (parent != nullptr) {
LOGE("DestroyLayoutNodeBeforeRemoveFromParent tag:" << node->tag().str());
int index = GetIndexForChild(parent, node);
if (index >= 0) {
RemoveLayoutNodeAtIndex(parent->id(), index);
}
}
}
void LayoutContext::UnlinkNodeFromChildren(LayoutNode* node) {
if (node == nullptr || node->children().empty()) return;
LOGE("DestroyLayoutNodeBeforeRemoveFromChildren tag:" << node->tag().str());
int count = static_cast<int>(node->children().size());
for (int i = count - 1; i >= 0; --i) {
RemoveLayoutNodeAtIndex(node->id(), i);
}
}
int LayoutContext::GetIndexForChild(LayoutNode* parent, LayoutNode* child) {
int index = 0;
bool found = false;
for (const auto& node : parent->children()) {
if (node == child) {
found = true;
break;
}
++index;
}
if (found) {
return index;
}
return -1;
}
void LayoutContext::AttachLayoutNodeType(int32_t id, const base::String& tag,
bool allow_inline,
const fml::RefPtr<PropBundle>& props) {
auto node = FindNodeById(id);
AttachLayoutNodeTypeInner(node, tag, allow_inline, props);
}
bool LayoutContext::NoNeedPlatformLayoutNode(
const base::String& tag, const fml::RefPtr<PropBundle>& props) {
// This map is used to store node tag names and props names without creating a
// platform layer Layoutnode key: tag name value: props name
const static base::NoDestructor<
std::unordered_map<std::string, std::unordered_set<std::string>>>
kCollection({{kImageComponent, {kAutoSizeAttribute}}});
bool no_needed = false;
auto it = kCollection->find(tag.str());
bool found = it != kCollection->end();
if (found) {
bool has_required = false;
for (const auto& attribute : it->second) {
if (props->Contains(attribute.c_str())) {
has_required = true;
}
}
if (!has_required) {
no_needed = true;
}
}
return no_needed;
}
void LayoutContext::AttachLayoutNodeTypeInner(
LayoutNode* node, const base::String& tag, bool allow_inline,
const fml::RefPtr<PropBundle>& props) {
if (node == nullptr) {
return;
}
auto it = node_type_recorder_.find(tag);
bool found = it != node_type_recorder_.end();
if (found) {
node->set_type(static_cast<LayoutNodeType>(it->second));
if (node->is_common() && !allow_inline) {
return;
}
}
if (root() && node->id() == root()->id()) {
node->set_type(LayoutNodeType::COMMON);
return;
}
if (NoNeedPlatformLayoutNode(tag, props)) {
node->set_type(LayoutNodeType::COMMON);
return;
}
TRACE_EVENT_BEGIN(LYNX_TRACE_CATEGORY, LAYOUT_CONTEXT_CREATE_NODE,
INSTANCE_ID, page_options_.GetInstanceID());
int result = platform_impl_->CreateLayoutNode(node->id(), tag.str(),
props.get(), allow_inline);
TRACE_EVENT_END(LYNX_TRACE_CATEGORY);
LayoutNodeType type = static_cast<LayoutNodeType>(result);
node->set_type(type);
// INLINE type should not be cached, since different parent will change the
// result
if (!found) {
if (!(type & INLINE)) {
node_type_recorder_.emplace(tag, type);
}
#if ENABLE_TESTBENCH_RECORDER
tasm::recorder::TestBenchBaseRecorder::GetInstance().RecordComponent(
tag.c_str(), type, record_id_);
#endif
}
}
void LayoutContext::MarkDirty(int32_t id) {
auto node = FindNodeById(id);
auto layout_node = node->FindNonVirtualNode();
if (layout_node) {
layout_node->MarkDirty();
}
}
LayoutNode* LayoutContext::FindNodeById(int32_t id) {
auto it = layout_nodes_.find(id);
if (it != layout_nodes_.end()) {
return &it->second;
}
return nullptr;
}
void LayoutContext::DispatchLayoutUpdates(
const std::shared_ptr<PipelineOptions>& options) {
TRACE_EVENT(LYNX_TRACE_CATEGORY, LAYOUT_CONTEXT_DISPATCH_LAYOUT_UPDATES);
tasm::timing::LongTaskMonitor::Scope longTaskScope(
page_options_, tasm::timing::kNativeFuncTask,
"LayoutContext::DispatchLayoutUpdates");
tasm::TimingCollector::Scope<Delegate> scope(delegate_.get(), options);
enable_layout_ = true;
DestroyPlatformNodesIfNeeded();
if (nullptr == root_ || !root_->slnode()) {
return;
}
// The results of Lynx C++ Layout need to be consumed during the platform
// layout cycle. Therefore, request platform layout first, and then execute
// Lynx Layout.
RequestLayout(options);
Layout(options);
}
void LayoutContext::UpdateFixedNodeSet(LayoutNode* node, bool is_insert) {
if (is_insert) {
fixed_node_set_.insert(node->slnode());
} else {
fixed_node_set_.erase(node->slnode());
}
}
void LayoutContext::CheckFixed(LayoutNode* node) {
// If PositionType has been changed, update the fixed node set.
if (node->slnode()->IsFixed() != node->slnode()->IsFixedBefore()) {
node->slnode()->SetIsFixedBefore(node->slnode()->IsFixed());
if (node->slnode()->IsFixed()) {
UpdateFixedNodeSet(node, true);
} else {
UpdateFixedNodeSet(node, false);
}
}
}
void LayoutContext::SetFontFaces(const CSSFontFaceRuleMap& fontfaces) {
platform_impl_->SetFontFaces(fontfaces);
}
void LayoutContext::SetLayoutEarlyExitTiming(
const std::shared_ptr<PipelineOptions>& options) {
if (options->need_timestamps) {
auto* timing_collector = tasm::TimingCollector::Instance();
timing_collector->Mark(tasm::timing::kLayoutStart);
if (options->enable_report_list_item_life_statistic_ &&
options->IsRenderListItem()) {
options->list_item_life_option_.start_layout_time_ =
base::CurrentTimeMicroseconds();
}
timing_collector->Mark(tasm::timing::kLayoutEnd);
if (options->enable_report_list_item_life_statistic_ &&
options->IsRenderListItem()) {
options->list_item_life_option_.end_layout_time_ =
base::CurrentTimeMicroseconds();
}
}
}
void LayoutContext::Layout(const std::shared_ptr<PipelineOptions>& options) {
std::string view_port_info_str = base::FormatString(
" for viewport, size: %.1f, %.1f; mode: %d, %d", viewport_.width,
viewport_.height, viewport_.width_mode, viewport_.height_mode);
TRACE_EVENT(LYNX_TRACE_CATEGORY_VITALS, LAYOUT_CONTEXT_LAYOUT,
[&options](lynx::perfetto::EventContext ctx) {
options->UpdateTraceDebugInfo(ctx.event());
});
if (layout_paused_) {
pipeline_options_for_paused_layouts_.emplace_back(options);
LOGI(
"[Layout] The layout has been paused and will be re-executed after "
"resuming."
<< view_port_info_str);
return;
}
if (root_ == nullptr || root_->slnode() == nullptr ||
!root_->slnode()->IsDirty()) {
if (root_ == nullptr || root_->slnode() == nullptr) {
LOGW(
"[Layout] Element or LayoutObject is not initialized "
"when Layout is called"
<< view_port_info_str);
} else {
LOGD("[Layout] Root is clean when layout is called"
<< view_port_info_str);
}
SetLayoutEarlyExitTiming(options);
delegate_->OnLayoutAfter(options);
return;
}
if (!enable_layout_ || !has_viewport_ready_) {
layout_wanted_ = true;
LOGI(
"[Layout] Layout is disabled or view port isn't ready when "
"Layout is called"
<< view_port_info_str);
SetLayoutEarlyExitTiming(options);
delegate_->OnLayoutAfter(options);
return;
};
UNUSED_LOG_VARIABLE auto time_begin = std::chrono::steady_clock::now();
if (SetViewportSizeToRootNode()) {
root()->MarkDirty();
}
if (options->need_timestamps) {
tasm::TimingCollector::Instance()->Mark(tasm::timing::kLayoutStart);
}
if (options->enable_report_list_item_life_statistic_ &&
options->IsRenderListItem()) {
options->list_item_life_option_.start_layout_time_ =
base::CurrentTimeMicroseconds();
}
// Dispatch OnLayoutBefore
LOGD("[Layout] Layout start" << view_port_info_str);
{
TRACE_EVENT(LYNX_TRACE_CATEGORY, LAYOUT_CONTEXT_DISPATCH_BEFORE_RECURSIVE);
DispatchLayoutBeforeRecursively(root_);
}
// CalculateLayout
LOGV("[Layout] Computing layout" << view_port_info_str);
{
TRACE_EVENT(LYNX_TRACE_CATEGORY_VITALS, LAYOUT_CONTEXT_CALCULATE_LAYOUT);
root_->CalculateLayout(GetFixedNodeSet());
}
LOGV("[Layout] Updating layout result" << view_port_info_str);
{
TRACE_EVENT(LYNX_TRACE_CATEGORY, LAYOUT_CONTEXT_LAYOUT_RECURSIVE);
LayoutRecursively(root(), options);
}
LOGV("[Layout] Dispatch layout after" << view_port_info_str);
if (options->need_timestamps) {
tasm::TimingCollector::Instance()->Mark(tasm::timing::kLayoutEnd);
}
if (options->enable_report_list_item_life_statistic_ &&
options->IsRenderListItem()) {
options->list_item_life_option_.end_layout_time_ =
base::CurrentTimeMicroseconds();
}
TRACE_EVENT(LYNX_TRACE_CATEGORY, LAYOUT_CONTEXT_ON_LAYOUT_AFTER);
auto root_size = root()->slnode()->GetLayoutResult().size_;
platform_impl_->UpdateRootSize(root_size.width_, root_size.height_);
// bundle_holder is transfer and captured by this layout finish callback
// and it is auto released at the end of this tasm loop
auto holder = platform_impl_->ReleasePlatformBundleHolder();
delegate_->OnLayoutAfter(options, std::move(holder), true);
has_layout_required_ = false;
layout_wanted_ = false;
// TODO(huzhanbo.luc): remove this when `OnFirstMeaningfulLayout` is removed
if (!has_first_page_layout_) {
// Set the flag first to avoid calling `OnFirstMeaningfulLayout` twice
has_first_page_layout_ = true;
delegate_->OnFirstMeaningfulLayout();
}
const auto& layout_result = root()->slnode()->GetLayoutResult();
// Notify that viewport / root size has changed
if ((calculated_viewport_.width != layout_result.size_.width_ ||
calculated_viewport_.height != layout_result.size_.height_)) {
calculated_viewport_.width = layout_result.size_.width_;
calculated_viewport_.height = layout_result.size_.height_;
CalculatedViewport viewport;
viewport.width =
calculated_viewport_.width / lynx_env_config_.LayoutsUnitPerPx();
viewport.height =
calculated_viewport_.height / lynx_env_config_.LayoutsUnitPerPx();
delegate_->OnCalculatedViewportChanged(viewport, root_id());
if (EnableEventReporter()) {
// update LynxView's size info for EventReporter
std::unordered_map<std::string, float> prop_map = {
{"lynxview_height", calculated_viewport_.height},
{"lynxview_width", calculated_viewport_.width}};
report::EventTracker::UpdateGenericInfo(page_options_.GetInstanceID(),
std::move(prop_map));
}
}
TRACE_EVENT_INSTANT(
LYNX_TRACE_CATEGORY, LAYOUT_CONTEXT_LAYOUT_RESULT,
[&](lynx::perfetto::EventContext ctx) {
ctx.event()->add_debug_annotations(
"width", base::FormatString("%.1f", layout_result.size_.width_));
ctx.event()->add_debug_annotations(
"height", base::FormatString("%.1f", layout_result.size_.height_));
ctx.event()->add_debug_annotations("viewport", view_port_info_str);
});
UNUSED_LOG_VARIABLE auto time_end = std::chrono::steady_clock::now();
LOGI("[Layout] layout finish with result size: "
<< layout_result.size_.width_ << ", " << layout_result.size_.height_
<< view_port_info_str << " Time taken: "
<< std::chrono::duration_cast<std::chrono::nanoseconds>(time_end -
time_begin)
.count()
<< " ns");
}
bool LayoutContext::ShouldSkipLayoutRecursively(LayoutNode* node) {
// Skip recursion for null nodes, or clean non-virtual nodes.
return node == nullptr || (!node->IsDirty() && !node->is_virtual());
}
void LayoutContext::DispatchLayoutBeforeRecursively(LayoutNode* node) {
if (ShouldSkipLayoutRecursively(node)) {
return;
}
if (node->slnode()->GetSLMeasureFunc()) {
platform_impl_->OnLayoutBefore(node->id());
}
for (auto& child : node->children()) {
DispatchLayoutBeforeRecursively(child);
}
}
void LayoutContext::UpdateLayoutInfo(LayoutNode* node) {
// Faster than use YGTransferLayoutOutputsRecursive in YGJNI.cc by 0.5 times
auto sl_node = node->slnode();
if (!sl_node) return;
const auto& layout_result = sl_node->GetLayoutResult();
float width = layout_result.size_.width_;
float height = layout_result.size_.height_;
float top = layout_result.offset_.Y();
float left = layout_result.offset_.X();
std::array<float, 4> paddings;
std::array<float, 4> margins;
std::array<float, 4> borders;
// paddings
paddings[0] = layout_result.padding_[starlight::kLeft];
paddings[1] = layout_result.padding_[starlight::kTop];
paddings[2] = layout_result.padding_[starlight::kRight];
paddings[3] = layout_result.padding_[starlight::kBottom];
// margins
margins[0] = layout_result.margin_[starlight::kLeft];
margins[1] = layout_result.margin_[starlight::kTop];
margins[2] = layout_result.margin_[starlight::kRight];
margins[3] = layout_result.margin_[starlight::kBottom];
// borders
borders[0] = layout_result.border_[starlight::kLeft];
borders[1] = layout_result.border_[starlight::kTop];
borders[2] = layout_result.border_[starlight::kRight];
borders[3] = layout_result.border_[starlight::kBottom];
std::array<float, 4>* sticky_positions = nullptr;
std::array<float, 4> sticky_pos_array;
if (sl_node->IsSticky()) {
bool enable_new_sticky = page_config_ && page_config_->GetEnableNewSticky();
// New sticky ignores nodes without left/top/right/bottom offsets.
if (!enable_new_sticky ||
(enable_new_sticky && sl_node->HasValidStickyPosInfo())) {
sticky_pos_array[0] = layout_result.sticky_pos_[starlight::kLeft];
sticky_pos_array[1] = layout_result.sticky_pos_[starlight::kTop];
sticky_pos_array[2] = layout_result.sticky_pos_[starlight::kRight];
sticky_pos_array[3] = layout_result.sticky_pos_[starlight::kBottom];
sticky_positions = &sticky_pos_array;
}
}
bool display_none = sl_node->GetShouldDisplayNone();
delegate_->OnLayoutUpdate(
node->id(), left, top, width, height, paddings, margins, borders,
sticky_positions, sl_node->GetCSSStyle()->GetMaxHeight().GetRawValue(),
display_none);
if (node->slnode()->GetSLMeasureFunc()) {
// Dispatch OnLayoutAfter to those nodes that have custom measure
platform_impl_->OnLayout(node->id(), left, top, width, height, paddings,
borders);
// if node has custom measure function, it may by need pass some bundle to
auto bundle = platform_impl_->GetPlatformExtraBundle(node->id());
if (!bundle) {
return;
}
delegate_->PostPlatformExtraBundle(node->id(), std::move(bundle));
}
}
void LayoutContext::LayoutRecursively(
LayoutNode* node, const std::shared_ptr<PipelineOptions>& options) {
if (ShouldSkipLayoutRecursively(node)) {
return;
}
if (IfNeedsUpdateLayoutInfo(node)) {
UpdateLayoutInfo(node);
}
for (auto& child : node->children()) {
LayoutRecursively(child, options);
}
node->MarkUpdated();
if (node->is_list_container()) {
if (pipeline_options_for_paused_layouts_.empty()) {
CollectDirtyNodeForList(node, options);
} else {
// If pipeline_options_for_paused_layouts_ is not empty,
// collect for all pipeline options in
// pipeline_options_for_paused_layouts_.
for (const auto& pending_pipeline_options :
pipeline_options_for_paused_layouts_) {
CollectDirtyNodeForList(node, pending_pipeline_options);
}
}
}
}
void LayoutContext::DestroyPlatformNodesIfNeeded() {
if (!destroyed_platform_nodes_.empty()) {
platform_impl_->DestroyLayoutNodes(destroyed_platform_nodes_);
destroyed_platform_nodes_.clear();