aboutsummaryrefslogtreecommitdiff
path: root/src/ui/controls/margin_container.cpp
diff options
context:
space:
mode:
authorcrupest <crupest@outlook.com>2018-09-25 13:08:40 +0800
committercrupest <crupest@outlook.com>2018-09-25 13:08:40 +0800
commit4b86554a0354d78efeb40e551eaccaac0fecd1d1 (patch)
treec8a73d848401f523ff91fe8ed1b0887aa88bbfb8 /src/ui/controls/margin_container.cpp
parentcea138417c54d6cf8043b6334c22e3af957d26f8 (diff)
downloadcru-4b86554a0354d78efeb40e551eaccaac0fecd1d1.tar.gz
cru-4b86554a0354d78efeb40e551eaccaac0fecd1d1.tar.bz2
cru-4b86554a0354d78efeb40e551eaccaac0fecd1d1.zip
Change the structure of project.
Diffstat (limited to 'src/ui/controls/margin_container.cpp')
-rw-r--r--src/ui/controls/margin_container.cpp63
1 files changed, 63 insertions, 0 deletions
diff --git a/src/ui/controls/margin_container.cpp b/src/ui/controls/margin_container.cpp
new file mode 100644
index 00000000..8f9101b2
--- /dev/null
+++ b/src/ui/controls/margin_container.cpp
@@ -0,0 +1,63 @@
+#include "margin_container.h"
+
+namespace cru::ui::controls
+{
+ inline float AtLeast0(const float value)
+ {
+ return value < 0 ? 0 : value;
+ }
+
+ inline Size AtLeast0(const Size& size)
+ {
+ return Size(AtLeast0(size.width), AtLeast0(size.height));
+ }
+
+ MarginContainer::MarginContainer(const Thickness& margin)
+ : Control(true), margin_(margin)
+ {
+ }
+
+ void MarginContainer::SetMargin(const Thickness& margin)
+ {
+ margin_ = margin;
+ Relayout();
+ }
+
+ Size MarginContainer::OnMeasure(const Size& available_size)
+ {
+ const auto margin_size = Size(margin_.left + margin_.right, margin_.top + margin_.bottom);
+ const auto coerced_available_size = AtLeast0(available_size - margin_size);
+ return Control::OnMeasure(coerced_available_size) + margin_size;
+ }
+
+ void MarginContainer::OnLayout(const Rect& rect)
+ {
+ const auto anchor = Point(margin_.left, margin_.top);
+ const auto margin_size = Size(margin_.left + margin_.right, margin_.top + margin_.bottom);
+ ForeachChild([anchor, margin_size, rect](Control* control)
+ {
+ const auto layout_params = control->GetLayoutParams();
+ const auto size = control->GetDesiredSize();
+
+ auto&& calculate_anchor = [](const float anchor, const Alignment alignment, const float layout_length, const float control_length) -> float
+ {
+ switch (alignment)
+ {
+ case Alignment::Center:
+ return anchor + (layout_length - control_length) / 2;
+ case Alignment::Start:
+ return anchor;
+ case Alignment::End:
+ return anchor + layout_length - control_length;
+ default:
+ UnreachableCode();
+ }
+ };
+
+ control->Layout(Rect(Point(
+ calculate_anchor(anchor.x, layout_params->width.alignment, rect.width - margin_size.width, size.width),
+ calculate_anchor(anchor.y, layout_params->height.alignment, rect.height - margin_size.height, size.height)
+ ), size));
+ });
+ }
+}