view_model_utils.cc 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. // Copyright (c) 2012 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include "ui/views/view_model_utils.h"
  5. #include <algorithm>
  6. #include "ui/views/view.h"
  7. #include "ui/views/view_model.h"
  8. namespace views {
  9. namespace {
  10. // Used in calculating ideal bounds.
  11. int primary_axis_coordinate(bool is_horizontal, const gfx::Point& point) {
  12. return is_horizontal ? point.x() : point.y();
  13. }
  14. } // namespace
  15. // static
  16. void ViewModelUtils::SetViewBoundsToIdealBounds(const ViewModelBase& model) {
  17. for (auto& entry : model.entries())
  18. entry.view->SetBoundsRect(entry.ideal_bounds);
  19. }
  20. // static
  21. bool ViewModelUtils::IsAtIdealBounds(const ViewModelBase& model) {
  22. return std::all_of(model.entries().begin(), model.entries().end(),
  23. [](const ViewModelBase::Entry& entry) {
  24. return entry.view->bounds() == entry.ideal_bounds;
  25. });
  26. }
  27. // static
  28. size_t ViewModelUtils::DetermineMoveIndex(const ViewModelBase& model,
  29. View* view,
  30. bool is_horizontal,
  31. int x,
  32. int y) {
  33. const auto& entries = model.entries();
  34. const int value = primary_axis_coordinate(is_horizontal, gfx::Point(x, y));
  35. DCHECK(model.GetIndexOfView(view).has_value());
  36. auto iter = entries.begin();
  37. for (; iter->view != view; ++iter) {
  38. const int mid_point = primary_axis_coordinate(
  39. is_horizontal, iter->ideal_bounds.CenterPoint());
  40. if (value < mid_point)
  41. return static_cast<size_t>(std::distance(entries.begin(), iter));
  42. }
  43. if (std::next(iter) == entries.end())
  44. return static_cast<size_t>(std::distance(entries.begin(), iter));
  45. // For indices after the current index ignore the bounds of the view being
  46. // dragged. This keeps the view from bouncing around as moved.
  47. const int delta = primary_axis_coordinate(
  48. is_horizontal, std::next(iter)->ideal_bounds.origin() -
  49. iter->ideal_bounds.origin().OffsetFromOrigin());
  50. for (++iter; iter != entries.end(); ++iter) {
  51. const int mid_point = primary_axis_coordinate(
  52. is_horizontal, iter->ideal_bounds.CenterPoint()) -
  53. delta;
  54. if (value < mid_point)
  55. return static_cast<size_t>(std::distance(entries.begin(), iter)) - 1;
  56. }
  57. return entries.size() - 1;
  58. }
  59. } // namespace views