Advertisement
kolbka_

Untitled

Dec 5th, 2021
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.57 KB | None | 0 0
  1. #ifndef BOX_H
  2. #define BOX_H
  3. #include "abstract_widgets.h"
  4.  
  5. namespace widgets {
  6. struct box final : container {
  7. enum struct kind { VERTICAL, HORIZONTAL };
  8.  
  9. private:
  10. const kind type;
  11. std::vector<std::unique_ptr<widget>> children;
  12.  
  13. public:
  14. explicit box(kind b) : type(b) {
  15. }
  16.  
  17. [[nodiscard]] int width() const final {
  18. return w_width;
  19. }
  20.  
  21. [[nodiscard]] int height() const final {
  22. return w_height;
  23. }
  24.  
  25. widget *child_at(int x, int y) final {
  26. if (this->widget::child_at(x, y) != nullptr) {
  27. int cur_x = 0;
  28. int cur_y = 0;
  29. for (auto &widget : children) {
  30. if (cur_x <= x && x < cur_x + widget->width() &&
  31. type == kind::HORIZONTAL) {
  32. int lower_border = (w_height - widget->height()) / 2;
  33. return widget->child_at(x - cur_x, y - lower_border);
  34. } else if (cur_y <= y && y < cur_y + widget->height() &&
  35. type == kind::VERTICAL) {
  36. int lower_border = (w_width - widget->width()) / 2;
  37. return widget->child_at(x - lower_border, y - cur_y);
  38. }
  39. cur_x += widget->width();
  40. cur_y += widget->height();
  41. }
  42. }
  43. return nullptr;
  44. }
  45.  
  46. [[nodiscard]] int size() const {
  47. return static_cast<int>(children.size());
  48. }
  49.  
  50. [[nodiscard]] widget *get(int index) const {
  51. return children[index].get();
  52. }
  53.  
  54. widget *add(std::unique_ptr<widget> child) {
  55. add_parent(child.get());
  56. children.emplace_back(std::move(child));
  57. update_layout();
  58. return children.back().get();
  59. }
  60.  
  61. auto remove(int index) {
  62. auto temp = std::move(children[index]);
  63. if (temp != nullptr) {
  64. remove_parent(temp.get());
  65. }
  66. children.erase(children.begin() + index); // hz
  67. update_layout();
  68. return temp;
  69. }
  70.  
  71. void update_layout() final {
  72. w_width = 0;
  73. w_height = 0;
  74. for (auto &widget : children) {
  75. if (type == kind::HORIZONTAL) {
  76. w_width += widget->width();
  77. w_height = std::max(w_height, widget->height());
  78. } else {
  79. w_height += widget->height();
  80. w_width = std::max(w_width, widget->width());
  81. }
  82. }
  83. }
  84. };
  85.  
  86. inline auto make_box(widgets::box::kind temp) {
  87. return std::make_unique<box>(temp);
  88. }
  89.  
  90. } // namespace widgets
  91.  
  92. #endif
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement