File: ui_element.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (744 lines) | stat: -rw-r--r-- 23,690 bytes parent folder | download | duplicates (6)
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
// Copyright 2016 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/vr/elements/ui_element.h"

#include <algorithm>
#include <limits>

#include "base/check_op.h"
#include "base/containers/adapters.h"
#include "base/notreached.h"
#include "base/numerics/angle_conversions.h"
#include "base/strings/string_split.h"
#include "base/strings/stringprintf.h"
#include "base/time/time.h"
#include "chrome/browser/vr/model/camera_model.h"
#include "device/vr/vr_gl_util.h"
#include "third_party/skia/include/core/SkRRect.h"
#include "third_party/skia/include/core/SkRect.h"
#include "ui/gfx/geometry/rect_f.h"

namespace vr {

namespace {

int AllocateId() {
  static int g_next_id = 1;
  return g_next_id++;
}

#ifndef NDEBUG
constexpr char kRed[] = "\x1b[31m";
constexpr char kGreen[] = "\x1b[32m";
constexpr char kBlue[] = "\x1b[34m";
constexpr char kCyan[] = "\x1b[36m";
constexpr char kYellow[] = "\x1b[33m";
constexpr char kReset[] = "\x1b[0m";

void DumpTransformOperations(const gfx::TransformOperations& ops,
                             std::ostringstream* os) {
  if (!ops.at(0).IsIdentity()) {
    const auto& translate = ops.at(0).translate;
    *os << "t(" << translate.x << ", " << translate.y << ", " << translate.z
        << ") ";
  }

  if (ops.size() < 2u) {
    return;
  }

  if (!ops.at(1).IsIdentity()) {
    const auto& rotate = ops.at(1).rotate;
    if (rotate.axis.x > 0.0f) {
      *os << "rx(" << rotate.angle << ") ";
    } else if (rotate.axis.y > 0.0f) {
      *os << "ry(" << rotate.angle << ") ";
    } else if (rotate.axis.z > 0.0f) {
      *os << "rz(" << rotate.angle << ") ";
    }
  }

  if (!ops.at(2).IsIdentity()) {
    const auto& scale = ops.at(2).scale;
    *os << "s(" << scale.x << ", " << scale.y << ", " << scale.z << ") ";
  }
}
#endif

}  // namespace

UiElement::UiElement() : id_(AllocateId()) {
  layout_offset_.AppendTranslate(0, 0, 0);
  transform_operations_.AppendTranslate(0, 0, 0);
  transform_operations_.AppendRotate(1, 0, 0, 0);
  transform_operations_.AppendScale(1, 1, 1);
}

UiElement::~UiElement() = default;

void UiElement::SetName(UiElementName name) {
  name_ = name;
}

void UiElement::SetType(UiElementType type) {
  type_ = type;
}

void UiElement::SetDrawPhase(DrawPhase draw_phase) {
  draw_phase_ = draw_phase;
}

void UiElement::Render(UiElementRenderer* renderer,
                       const CameraModel& model) const {
  // Elements without an overridden implementation of Render should have their
  // draw phase set to kPhaseNone and should, consequently, be filtered out when
  // the UiRenderer collects elements to draw. Therefore, if we invoke this
  // function, it is an error.
  NOTREACHED() << "element: " << DebugName();
}

void UiElement::Initialize(SkiaSurfaceProvider* provider) {}

bool UiElement::DoBeginFrame(const gfx::Transform& head_pose,
                             bool force_animations_to_completion) {
  // TODO(mthiesse): This is overly cautious. We may have keyframe_models but
  // not trigger any updates, so we should refine this logic and have
  // KeyframeEffect::Tick return a boolean. Similarly, the bindings update
  // may have had no visual effect and dirtiness should be related to setting
  // properties that do indeed cause visual updates.
  bool keyframe_models_updated = !animator_.keyframe_models().empty();
  if (force_animations_to_completion) {
    animator_.FinishAll();
  } else {
    animator_.Tick(last_frame_time_);
  }
  set_update_phase(kUpdatedAnimations);
  bool begin_frame_updated = OnBeginFrame(head_pose);
  UpdateComputedOpacity();
  bool was_visible_at_any_point = IsVisible() ||
                                  updated_visibility_this_frame_ ||
                                  IsOrWillBeLocallyVisible();
  bool dirty = (begin_frame_updated || keyframe_models_updated ||
                updated_bindings_this_frame_) &&
               was_visible_at_any_point;

  if (was_visible_at_any_point) {
    for (auto& child : children_)
      dirty |= child->DoBeginFrame(head_pose, force_animations_to_completion);
  }

  return dirty;
}

bool UiElement::OnBeginFrame(const gfx::Transform& head_pose) {
  return false;
}

bool UiElement::PrepareToDraw() {
  return false;
}

bool UiElement::HasDirtyTexture() const {
  return false;
}

void UiElement::UpdateTexture() {}

void UiElement::SetSize(float width, float height) {
  animator_.TransitionSizeTo(this, last_frame_time_, BOUNDS, size_,
                             gfx::SizeF(width, height));
}

void UiElement::SetVisible(bool visible) {
  SetOpacity(visible ? opacity_when_visible_ : 0.0);
}

void UiElement::SetVisibleImmediately(bool visible) {
  opacity_ = visible ? opacity_when_visible_ : 0.0;
  animator_.RemoveKeyframeModels(OPACITY);
}

bool UiElement::IsVisible() const {
  // Many things rely on checking element visibility, including tests.
  // Therefore, support reporting visibility even if an element sits in an
  // invisible portion of the tree.  We can infer that if the scene computed
  // opacities, but this element did not, it must be invisible.
  DCHECK(update_phase_ >= kUpdatedComputedOpacity ||
         FrameLifecycle::phase() >= kUpdatedComputedOpacity);
  // TODO(crbug.com/41382805): we shouldn't need to check opacity() here.
  return update_phase_ >= kUpdatedComputedOpacity && opacity() > 0.0f &&
         computed_opacity() > 0.0f;
}

bool UiElement::IsOrWillBeLocallyVisible() const {
  return opacity() > 0.0f || GetTargetOpacity() > 0.0f;
}

gfx::SizeF UiElement::size() const {
  DCHECK_LE(kUpdatedSize, update_phase_);
  return size_;
}

void UiElement::SetLayoutOffset(float x, float y) {
  if (x_centering() == LEFT) {
    x += size_.width() / 2;
    if (!bounds_contain_padding_)
      x -= left_padding_;
  } else if (x_centering() == RIGHT) {
    x -= size_.width() / 2;
    if (!bounds_contain_padding_)
      x += right_padding_;
  }
  if (y_centering() == TOP) {
    y -= size_.height() / 2;
    if (!bounds_contain_padding_)
      y += top_padding_;
  } else if (y_centering() == BOTTOM) {
    y += size_.height() / 2;
    if (!bounds_contain_padding_)
      y -= bottom_padding_;
  }

  if (x == layout_offset_.at(0).translate.x &&
      y == layout_offset_.at(0).translate.y &&
      !IsAnimatingProperty(LAYOUT_OFFSET)) {
    return;
  }

  gfx::TransformOperations operations = layout_offset_;
  gfx::TransformOperation& op = operations.at(0);
  op.translate = {x, y, 0};
  op.Bake();
  animator_.TransitionTransformOperationsTo(
      this, last_frame_time_, LAYOUT_OFFSET, layout_offset_, operations);
}

void UiElement::SetTranslate(float x, float y, float z) {
  if (x == transform_operations_.at(kTranslateIndex).translate.x &&
      y == transform_operations_.at(kTranslateIndex).translate.y &&
      z == transform_operations_.at(kTranslateIndex).translate.z &&
      !IsAnimatingProperty(TRANSFORM)) {
    return;
  }

  gfx::TransformOperations operations = transform_operations_;
  gfx::TransformOperation& op = operations.at(kTranslateIndex);
  op.translate = {x, y, z};
  op.Bake();
  animator_.TransitionTransformOperationsTo(this, last_frame_time_, TRANSFORM,
                                            transform_operations_, operations);
}

void UiElement::SetRotate(float x, float y, float z, float radians) {
  float degrees = base::RadToDeg(radians);

  if (x == transform_operations_.at(kRotateIndex).rotate.axis.x &&
      y == transform_operations_.at(kRotateIndex).rotate.axis.y &&
      z == transform_operations_.at(kRotateIndex).rotate.axis.z &&
      degrees == transform_operations_.at(kRotateIndex).rotate.angle &&
      !IsAnimatingProperty(TRANSFORM)) {
    return;
  }

  gfx::TransformOperations operations = transform_operations_;
  gfx::TransformOperation& op = operations.at(kRotateIndex);
  op.rotate.axis = {x, y, z};
  op.rotate.angle = degrees;
  op.Bake();
  animator_.TransitionTransformOperationsTo(this, last_frame_time_, TRANSFORM,
                                            transform_operations_, operations);
}

void UiElement::SetScale(float x, float y, float z) {
  if (x == transform_operations_.at(kScaleIndex).scale.x &&
      y == transform_operations_.at(kScaleIndex).scale.y &&
      z == transform_operations_.at(kScaleIndex).scale.z &&
      !IsAnimatingProperty(TRANSFORM)) {
    return;
  }

  gfx::TransformOperations operations = transform_operations_;
  gfx::TransformOperation& op = operations.at(kScaleIndex);
  op.scale = {x, y, z};
  op.Bake();
  animator_.TransitionTransformOperationsTo(this, last_frame_time_, TRANSFORM,
                                            transform_operations_, operations);
}

void UiElement::SetOpacity(float opacity) {
  animator_.TransitionFloatTo(this, last_frame_time_, OPACITY, opacity_,
                              opacity);
}

void UiElement::SetCornerRadii(const CornerRadii& radii) {
  corner_radii_ = radii;
}

gfx::SizeF UiElement::GetTargetSize() const {
  return animator_.GetTargetSizeValue(TargetProperty::BOUNDS, size_);
}

gfx::TransformOperations UiElement::GetTargetTransform() const {
  return animator_.GetTargetTransformOperationsValue(TargetProperty::TRANSFORM,
                                                     transform_operations_);
}

gfx::Transform UiElement::ComputeTargetWorldSpaceTransform() const {
  gfx::Transform m;
  for (const UiElement* current = this; current; current = current->parent()) {
    m.PostConcat(current->GetTargetLocalTransform());
  }
  return m;
}

float UiElement::GetTargetOpacity() const {
  return animator_.GetTargetFloatValue(TargetProperty::OPACITY, opacity_);
}

float UiElement::ComputeTargetOpacity() const {
  float opacity = 1.0;
  for (const UiElement* current = this; current; current = current->parent()) {
    opacity *= current->GetTargetOpacity();
  }
  return opacity;
}

float UiElement::computed_opacity() const {
  DCHECK_LE(kUpdatedComputedOpacity, update_phase_) << DebugName();
  return computed_opacity_;
}

const gfx::Transform& UiElement::world_space_transform() const {
  DCHECK_LE(kUpdatedWorldSpaceTransform, update_phase_);
  return world_space_transform_;
}

bool UiElement::IsWorldPositioned() const {
  return true;
}

std::string UiElement::DebugName() const {
  return base::StringPrintf(
      "%s%s%s",
      UiElementNameToString(name() == kNone ? owner_name_for_test() : name())
          .c_str(),
      type() == kTypeNone ? "" : ":",
      type() == kTypeNone ? "" : UiElementTypeToString(type()).c_str());
}

#ifndef NDEBUG
void DumpLines(const std::vector<size_t>& counts,
               const std::vector<const UiElement*>& ancestors,
               std::ostringstream* os) {
  for (size_t i = 0; i < counts.size(); ++i) {
    size_t current_count = counts[i];
    if (i + 1 < counts.size()) {
      current_count++;
    }
    if (ancestors[ancestors.size() - i - 1]->children().size() >
        current_count) {
      *os << "| ";
    } else {
      *os << "  ";
    }
  }
}

void UiElement::DumpHierarchy(std::vector<size_t> counts,
                              std::ostringstream* os,
                              bool include_bindings) const {
  // Put our ancestors in a vector for easy reverse traversal.
  std::vector<const UiElement*> ancestors;
  for (const UiElement* ancestor = parent(); ancestor;
       ancestor = ancestor->parent()) {
    ancestors.push_back(ancestor);
  }
  DCHECK_EQ(counts.size(), ancestors.size());

  *os << kBlue;
  for (size_t i = 0; i < counts.size(); ++i) {
    if (i + 1 == counts.size()) {
      *os << "+-";
    } else if (ancestors[ancestors.size() - i - 1]->children().size() >
               counts[i] + 1) {
      *os << "| ";
    } else {
      *os << "  ";
    }
  }
  *os << kReset;

  if (update_phase_ < kUpdatedComputedOpacity || !IsVisible()) {
    *os << kBlue;
  }

  *os << DebugName() << kReset << " " << kCyan << DrawPhaseToString(draw_phase_)
      << " " << kReset;

  if (update_phase_ >= kUpdatedSize) {
    if (size().width() != 0.0f || size().height() != 0.0f) {
      *os << kRed << "[" << size().width() << ", " << size().height() << "] "
          << kReset;
    }
  }

  if (update_phase_ >= kUpdatedWorldSpaceTransform) {
    *os << kGreen;
    DumpGeometry(os);
  }

  counts.push_back(0u);

  if (include_bindings) {
    std::ostringstream binding_stream;
    for (auto& binding : bindings_) {
      std::string binding_text = binding->ToString();
      if (binding_text.empty())
        continue;
      binding_stream << binding->ToString() << std::endl;
    }

    auto split_bindings =
        base::SplitString(binding_stream.str(), "\n", base::TRIM_WHITESPACE,
                          base::SPLIT_WANT_NONEMPTY);
    if (!split_bindings.empty()) {
      ancestors.insert(ancestors.begin(), this);
    }
    for (const auto& split : split_bindings) {
      *os << std::endl << kBlue;
      DumpLines(counts, ancestors, os);
      *os << kGreen << split;
    }
  }

  *os << kReset << std::endl;

  for (auto& child : children_) {
    child->DumpHierarchy(counts, os, include_bindings);
    counts.back()++;
  }
}

void UiElement::DumpGeometry(std::ostringstream* os) const {
  DumpTransformOperations(transform_operations_, os);
  *os << kYellow;
  DumpTransformOperations(layout_offset_, os);
}
#endif

void UiElement::AddChild(std::unique_ptr<UiElement> child) {
  for (UiElement* current = this; current; current = current->parent())
    current->set_descendants_updated(true);
  child->parent_ = this;
  children_.push_back(std::move(child));
}

std::unique_ptr<UiElement> UiElement::RemoveChild(UiElement* to_remove) {
  return ReplaceChild(to_remove, nullptr);
}

std::unique_ptr<UiElement> UiElement::ReplaceChild(
    UiElement* to_remove,
    std::unique_ptr<UiElement> to_add) {
  for (UiElement* current = this; current; current = current->parent())
    current->set_descendants_updated(true);
  DCHECK_EQ(this, to_remove->parent_);
  to_remove->parent_ = nullptr;
  size_t old_size = children_.size();

  auto it =
      std::ranges::find(children_, to_remove, &std::unique_ptr<UiElement>::get);
  DCHECK(it != std::end(children_));

  std::unique_ptr<UiElement> removed(it->release());
  if (to_add) {
    to_add->parent_ = this;
    *it = std::move(to_add);
  } else {
    children_.erase(it);
    DCHECK_EQ(old_size - 1, children_.size());
  }
  return removed;
}

void UiElement::AddBinding(std::unique_ptr<BindingBase> binding) {
  bindings_.push_back(std::move(binding));
}

void UiElement::UpdateBindings() {
  bool should_recur = IsOrWillBeLocallyVisible();
  updated_bindings_this_frame_ = false;
  for (auto& binding : bindings_) {
    if (binding->Update())
      updated_bindings_this_frame_ = true;
  }
  should_recur |= IsOrWillBeLocallyVisible();

  set_update_phase(kUpdatedBindings);
  if (!should_recur)
    return;

  for (auto& child : children_)
    child->UpdateBindings();
}

gfx::Point3F UiElement::GetCenter() const {
  return world_space_transform_.MapPoint(gfx::Point3F());
}

void UiElement::OnFloatAnimated(const float& value,
                                int target_property_id,
                                gfx::KeyframeModel* keyframe_model) {
  opacity_ = std::clamp(value, 0.0f, 1.0f);
}

void UiElement::OnTransformAnimated(const gfx::TransformOperations& operations,
                                    int target_property_id,
                                    gfx::KeyframeModel* keyframe_model) {
  if (target_property_id == TRANSFORM) {
    transform_operations_ = operations;
  } else if (target_property_id == LAYOUT_OFFSET) {
    layout_offset_ = operations;
  } else {
    NOTREACHED();
  }
  local_transform_ = layout_offset_.Apply() * transform_operations_.Apply();
  world_space_transform_dirty_ = true;
}

void UiElement::OnSizeAnimated(const gfx::SizeF& size,
                               int target_property_id,
                               gfx::KeyframeModel* keyframe_model) {
  if (size_ == size)
    return;
  size_ = size;
  world_space_transform_dirty_ = true;
}

void UiElement::OnColorAnimated(const SkColor& size,
                                int target_property_id,
                                gfx::KeyframeModel* keyframe_model) {}

void UiElement::SetTransitionedProperties(
    const std::set<TargetProperty>& properties) {
  std::set<int> converted_properties(properties.begin(), properties.end());
  animator_.SetTransitionedProperties(converted_properties);
}

void UiElement::AddKeyframeModel(
    std::unique_ptr<gfx::KeyframeModel> keyframe_model) {
  animator_.AddKeyframeModel(std::move(keyframe_model));
}

void UiElement::RemoveKeyframeModels(int target_property) {
  animator_.RemoveKeyframeModels(target_property);
}

bool UiElement::IsAnimatingProperty(TargetProperty property) const {
  return animator_.IsAnimatingProperty(static_cast<int>(property));
}

bool UiElement::SizeAndLayOut() {
  if (!IsVisible() && !IsOrWillBeLocallyVisible())
    return false;

  // May be overridden by layout elements.
  bool changed = SizeAndLayOutChildren();

  changed |= PrepareToDraw();

  LayOutContributingChildren();

  if (bounds_contain_children_) {
    gfx::RectF bounds = ComputeContributingChildrenBounds();
    if (bounds.size() != GetTargetSize())
      SetSize(bounds.width(), bounds.height());
  } else {
    DCHECK_EQ(0.0f, right_padding_);
    DCHECK_EQ(0.0f, left_padding_);
    DCHECK_EQ(0.0f, top_padding_);
    DCHECK_EQ(0.0f, bottom_padding_);
  }
  set_update_phase(kUpdatedSize);

  LayOutNonContributingChildren();

  set_update_phase(kUpdatedLayout);
  return changed;
}

bool UiElement::SizeAndLayOutChildren() {
  bool changed = false;
  for (auto& child : children_)
    changed |= child->SizeAndLayOut();
  return changed;
}

gfx::RectF UiElement::ComputeContributingChildrenBounds() {
  gfx::RectF bounds;
  for (auto& child : children_) {
    if (!child->IsVisible() || !child->contributes_to_parent_bounds())
      continue;

    gfx::RectF outer_bounds(child->size());
    gfx::RectF inner_bounds(child->size());
    if (!child->bounds_contain_padding_) {
      inner_bounds.Inset(
          gfx::InsetsF::TLBR(child->top_padding_, child->left_padding_,
                             child->bottom_padding_, child->right_padding_));
    }
    gfx::SizeF size = inner_bounds.size();
    if (size.IsEmpty())
      continue;

    gfx::Vector2dF delta =
        outer_bounds.CenterPoint() - inner_bounds.CenterPoint();
    gfx::Point3F child_center(child->local_origin() - delta);
    gfx::Vector3dF corner_offset(size.width(), size.height(), 0);
    corner_offset.Scale(-0.5);
    gfx::Point3F child_upper_left = child_center + corner_offset;
    gfx::Point3F child_lower_right = child_center - corner_offset;

    child_upper_left = child->LocalTransform().MapPoint(child_upper_left);
    child_lower_right = child->LocalTransform().MapPoint(child_lower_right);
    gfx::RectF local_rect =
        gfx::RectF(child_upper_left.x(), child_upper_left.y(),
                   child_lower_right.x() - child_upper_left.x(),
                   child_lower_right.y() - child_upper_left.y());
    bounds.Union(local_rect);
  }

  bounds.Inset(gfx::InsetsF::TLBR(-top_padding_, -left_padding_,
                                  -bottom_padding_, -right_padding_));
  bounds.set_origin(bounds.CenterPoint());
  if (local_origin_ != bounds.origin()) {
    world_space_transform_dirty_ = true;
    local_origin_ = bounds.origin();
  }

  return bounds;
}

void UiElement::LayOutContributingChildren() {
  for (auto& child : children_) {
    if (!child->IsVisible() || !child->contributes_to_parent_bounds())
      continue;
    // Nothing to actually do since we aren't a layout object.  Children that
    // contribute to parent bounds cannot center or anchor to the edge of the
    // parent.
    DCHECK_EQ(child->x_centering(), NONE) << child->DebugName();
    DCHECK_EQ(child->y_centering(), NONE) << child->DebugName();
    DCHECK_EQ(child->x_anchoring(), NONE) << child->DebugName();
    DCHECK_EQ(child->y_anchoring(), NONE) << child->DebugName();
  }
}

void UiElement::LayOutNonContributingChildren() {
  DCHECK_LE(kUpdatedSize, update_phase_);
  for (auto& child : children_) {
    if (!child->IsVisible() || child->contributes_to_parent_bounds())
      continue;

    // To anchor a child, use the parent's size to find its edge.
    float x_offset = 0.0f;
    if (child->x_anchoring() == LEFT) {
      x_offset = -0.5f * size().width();
      if (!child->bounds_contain_padding())
        x_offset += left_padding_;
    } else if (child->x_anchoring() == RIGHT) {
      x_offset = 0.5f * size().width();
      if (!child->bounds_contain_padding())
        x_offset -= right_padding_;
    }
    float y_offset = 0.0f;
    if (child->y_anchoring() == TOP) {
      y_offset = 0.5f * size().height();
      if (!child->bounds_contain_padding())
        y_offset -= top_padding_;
    } else if (child->y_anchoring() == BOTTOM) {
      y_offset = -0.5f * size().height();
      if (!child->bounds_contain_padding())
        y_offset += bottom_padding_;
    }
    child->SetLayoutOffset(x_offset, y_offset);
  }
}

gfx::RectF UiElement::GetClipRect() const {
  auto corner_origin = clip_rect_.origin() - gfx::Vector2dF(-0.5f, 0.5f);
  return gfx::RectF({corner_origin.x(), -corner_origin.y()}, clip_rect_.size());
}

void UiElement::SetClipRect(const gfx::RectF& rect) {
  auto new_origin = gfx::PointF(rect.origin().x(), -rect.origin().y()) +
                    gfx::Vector2dF(-0.5f, 0.5f);
  clip_rect_ = gfx::RectF(new_origin, rect.size());
}

void UiElement::UpdateComputedOpacity() {
  bool was_visible = computed_opacity_ > 0.0f;
  set_computed_opacity(opacity_);
  if (parent_) {
    set_computed_opacity(computed_opacity_ * parent_->computed_opacity());
  }
  set_update_phase(kUpdatedComputedOpacity);
  updated_visibility_this_frame_ = IsVisible() != was_visible;
}

bool UiElement::UpdateWorldSpaceTransform(bool parent_changed) {
  if (!IsVisible() && !updated_visibility_this_frame_)
    return false;

  bool changed = false;
  bool should_update = ShouldUpdateWorldSpaceTransform(parent_changed);
  if (should_update) {
    gfx::Transform transform;
    transform.Translate(local_origin_.x(), local_origin_.y());

    if (!size_.IsEmpty()) {
      transform.Scale(size_.width(), size_.height());
    }

    // Compute an inheritable transformation that can be applied to this
    // element, and it's children, if applicable.
    gfx::Transform inheritable = LocalTransform();

    if (parent_) {
      inheritable.PostConcat(parent_->inheritable_transform());
    }

    transform.PostConcat(inheritable);
    changed = !transform.ApproximatelyEqual(world_space_transform_) ||
              !inheritable.ApproximatelyEqual(inheritable_transform_);
    set_world_space_transform(transform);
    set_inheritable_transform(inheritable);
  }

  bool child_changed = false;
  set_update_phase(kUpdatedWorldSpaceTransform);
  for (auto& child : children_) {
    // TODO(crbug.com/41393128): it's unfortunate that we're not passing down
    // the same dirtiness signal that we return. I.e., we'd ideally use
    // |changed| here.
    child_changed |= child->UpdateWorldSpaceTransform(should_update);
  }

  return changed || child_changed;
}

gfx::Transform UiElement::LocalTransform() const {
  return local_transform_;
}

gfx::Transform UiElement::GetTargetLocalTransform() const {
  return layout_offset_.Apply() * GetTargetTransform().Apply();
}

bool UiElement::ShouldUpdateWorldSpaceTransform(
    bool parent_transform_changed) const {
  return parent_transform_changed || world_space_transform_dirty_;
}

}  // namespace vr