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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
|
#include "control.hpp"
#include <algorithm>
#include "window.hpp"
#include "application.hpp"
#include "graph/graph.hpp"
#include "exception.hpp"
#include "cru_debug.hpp"
#include "convert_util.hpp"
#include "math_util.hpp"
#ifdef CRU_DEBUG_LAYOUT
#include "ui_manager.hpp"
#endif
namespace cru::ui
{
using namespace events;
Control::Control(const bool container) :
is_container_(container)
{
}
Control::Control(WindowConstructorTag, Window* window) : Control(true)
{
window_ = window;
}
Control::~Control()
{
for (auto control: GetChildren())
{
delete control;
}
}
void AddChildCheck(Control* control)
{
if (control->GetParent() != nullptr)
throw std::invalid_argument("The control already has a parent.");
if (dynamic_cast<Window*>(control))
throw std::invalid_argument("Can't add a window as child.");
}
const std::vector<Control*>& Control::GetChildren() const
{
return children_;
}
void Control::AddChild(Control* control)
{
ThrowIfNotContainer();
AddChildCheck(control);
this->children_.push_back(control);
control->parent_ = this;
this->OnAddChild(control);
}
void Control::AddChild(Control* control, int position)
{
ThrowIfNotContainer();
AddChildCheck(control);
if (position < 0 || static_cast<decltype(this->children_.size())>(position) > this->children_.size())
throw std::invalid_argument("The position is out of range.");
this->children_.insert(this->children_.cbegin() + position, control);
control->parent_ = this;
this->OnAddChild(this);
}
void Control::RemoveChild(Control* child)
{
ThrowIfNotContainer();
const auto i = std::find(this->children_.cbegin(), this->children_.cend(), child);
if (i == this->children_.cend())
throw std::invalid_argument("The argument child is not a child of this control.");
this->children_.erase(i);
child->parent_ = nullptr;
this->OnRemoveChild(this);
}
void Control::RemoveChild(const int position)
{
ThrowIfNotContainer();
if (position < 0 || static_cast<decltype(this->children_.size())>(position) >= this->children_.size())
throw std::invalid_argument("The position is out of range.");
const auto p = children_.cbegin() + position;
const auto child = *p;
children_.erase(p);
child->parent_ = nullptr;
this->OnRemoveChild(child);
}
Control* Control::GetAncestor()
{
// if attached to window, the window is the ancestor.
if (window_)
return window_;
// otherwise find the ancestor
auto ancestor = this;
while (const auto parent = ancestor->GetParent())
ancestor = parent;
return ancestor;
}
void TraverseDescendantsInternal(Control* control, const std::function<void(Control*)>& predicate)
{
predicate(control);
if (control->IsContainer())
for (auto c: control->GetChildren())
{
TraverseDescendantsInternal(c, predicate);
}
}
void Control::TraverseDescendants(const std::function<void(Control*)>& predicate)
{
if (is_container_)
TraverseDescendantsInternal(this, predicate);
else
predicate(this);
}
Point Control::GetPositionRelative()
{
return position_;
}
void Control::SetPositionRelative(const Point & position)
{
if (position != position_)
{
if (old_position_ == position) // if cache has been refreshed and no pending notify
old_position_ = position_;
position_ = position;
LayoutManager::GetInstance()->InvalidateControlPositionCache(this);
if (auto window = GetWindow())
{
window->InvalidateDraw();
}
}
}
Size Control::GetSize()
{
return size_;
}
void Control::SetSize(const Size & size)
{
const auto old_size = size_;
size_ = size;
SizeChangedEventArgs args(this, this, old_size, size);
RaiseSizeChangedEvent(args);
if (auto window = GetWindow())
window->InvalidateDraw();
}
Point Control::GetPositionAbsolute() const
{
return position_cache_.lefttop_position_absolute;
}
Point Control::ControlToWindow(const Point& point) const
{
return Point(point.x + position_cache_.lefttop_position_absolute.x,
point.y + position_cache_.lefttop_position_absolute.y);
}
Point Control::WindowToControl(const Point & point) const
{
return Point(point.x - position_cache_.lefttop_position_absolute.x,
point.y - position_cache_.lefttop_position_absolute.y);
}
bool Control::IsPointInside(const Point & point)
{
const auto border_geometry = geometry_info_.border_geometry;
if (border_geometry != nullptr)
{
if (IsBordered())
{
BOOL contains;
border_geometry->FillContainsPoint(Convert(point), D2D1::Matrix3x2F::Identity(), &contains);
if (!contains)
border_geometry->StrokeContainsPoint(Convert(point), GetBorderProperty().GetStrokeWidth(), nullptr, D2D1::Matrix3x2F::Identity(), &contains);
return contains != 0;
}
else
{
BOOL contains;
border_geometry->FillContainsPoint(Convert(point), D2D1::Matrix3x2F::Identity(), &contains);
return contains != 0;
}
}
return false;
}
Control* Control::HitTest(const Point& point)
{
const auto point_inside = IsPointInside(point);
if (IsClipContent())
{
if (!point_inside)
return nullptr;
if (geometry_info_.content_geometry != nullptr)
{
BOOL contains;
ThrowIfFailed(geometry_info_.content_geometry->FillContainsPoint(Convert(point), D2D1::Matrix3x2F::Identity(), &contains));
if (contains == 0)
return this;
}
}
const auto& children = GetChildren();
for (auto i = children.crbegin(); i != children.crend(); ++i)
{
const auto&& lefttop = (*i)->GetPositionRelative();
const auto&& coerced_point = Point(point.x - lefttop.x, point.y - lefttop.y);
const auto child_hit_test_result = (*i)->HitTest(coerced_point);
if (child_hit_test_result != nullptr)
return child_hit_test_result;
}
return point_inside ? this : nullptr;
}
void Control::SetClipContent(const bool clip)
{
if (clip_content_ == clip)
return;
clip_content_ = clip;
InvalidateDraw();
}
void Control::Draw(ID2D1DeviceContext* device_context)
{
D2D1::Matrix3x2F old_transform;
device_context->GetTransform(&old_transform);
const auto position = GetPositionRelative();
device_context->SetTransform(old_transform * D2D1::Matrix3x2F::Translation(position.x, position.y));
OnDrawDecoration(device_context);
const auto set_layer = geometry_info_.content_geometry != nullptr && IsClipContent();
if (set_layer)
device_context->PushLayer(D2D1::LayerParameters(D2D1::InfiniteRect(), geometry_info_.content_geometry.Get()), nullptr);
OnDrawCore(device_context);
for (auto child : GetChildren())
child->Draw(device_context);
if (set_layer)
device_context->PopLayer();
device_context->SetTransform(old_transform);
}
void Control::InvalidateDraw()
{
if (window_ != nullptr)
window_->InvalidateDraw();
}
bool Control::RequestFocus()
{
auto window = GetWindow();
if (window == nullptr)
return false;
return window->RequestFocusFor(this);
}
bool Control::HasFocus()
{
auto window = GetWindow();
if (window == nullptr)
return false;
return window->GetFocusControl() == this;
}
void Control::InvalidateLayout()
{
if (const auto window = GetWindow())
window->WindowInvalidateLayout();
}
void Control::Measure(const Size& available_size)
{
SetDesiredSize(OnMeasureCore(available_size));
}
void Control::Layout(const Rect& rect)
{
SetPositionRelative(rect.GetLeftTop());
SetSize(rect.GetSize());
AfterLayoutSelf();
OnLayoutCore(Rect(Point::Zero(), rect.GetSize()));
}
Size Control::GetDesiredSize() const
{
return desired_size_;
}
void Control::SetDesiredSize(const Size& desired_size)
{
desired_size_ = desired_size;
}
inline void Shrink(Rect& rect, const Thickness& thickness)
{
rect.left += thickness.left;
rect.top += thickness.top;
rect.width -= thickness.GetHorizontalTotal();
rect.height -= thickness.GetVerticalTotal();
}
Rect Control::GetRect(const RectRange range)
{
if (GetSize() == Size::Zero())
return Rect();
const auto layout_params = GetLayoutParams();
auto result = Rect(Point::Zero(), GetSize());
if (range == RectRange::Margin)
return result;
Shrink(result, layout_params->margin);
if (range == RectRange::FullBorder)
return result;
if (is_bordered_)
Shrink(result, Thickness(GetBorderProperty().GetStrokeWidth() / 2.0f));
if (range == RectRange::HalfBorder)
return result;
if (is_bordered_)
Shrink(result, Thickness(GetBorderProperty().GetStrokeWidth() / 2.0f));
if (range == RectRange::Padding)
return result;
Shrink(result, layout_params->padding);
return result;
}
Point Control::TransformPoint(const Point& point, const RectRange from, const RectRange to)
{
const auto rect_from = GetRect(from);
const auto rect_to = GetRect(to);
auto p = point;
p.x += rect_from.left;
p.y += rect_from.top;
p.x -= rect_to.left;
p.y -= rect_to.top;
return p;
}
void Control::UpdateBorder()
{
RegenerateGeometryInfo();
InvalidateLayout();
InvalidateDraw();
}
void Control::SetBordered(const bool bordered)
{
if (bordered != is_bordered_)
{
is_bordered_ = bordered;
UpdateBorder();
}
}
void Control::SetCursor(const Cursor::Ptr& cursor)
{
if (cursor != cursor_)
{
cursor_ = cursor;
const auto window = GetWindow();
if (window && window->GetMouseHoverControl() == this)
window->UpdateCursor();
}
}
void Control::OnAddChild(Control* child)
{
if (auto window = GetWindow())
{
child->TraverseDescendants([window](Control* control) {
control->OnAttachToWindow(window);
});
InvalidateLayout();
}
}
void Control::OnRemoveChild(Control* child)
{
if (auto window = GetWindow())
{
child->TraverseDescendants([window](Control* control) {
control->OnDetachToWindow(window);
});
InvalidateLayout();
}
}
void Control::OnAttachToWindow(Window* window)
{
window_ = window;
}
void Control::OnDetachToWindow(Window * window)
{
window_ = nullptr;
}
void Control::OnDrawDecoration(ID2D1DeviceContext* device_context)
{
#ifdef CRU_DEBUG_LAYOUT
if (GetWindow()->IsDebugLayout())
{
if (padding_geometry_ != nullptr)
device_context->FillGeometry(padding_geometry_.Get(), UiManager::GetInstance()->GetPredefineResources()->debug_layout_padding_brush.Get());
if (margin_geometry_ != nullptr)
device_context->FillGeometry(margin_geometry_.Get(), UiManager::GetInstance()->GetPredefineResources()->debug_layout_margin_brush.Get());
device_context->DrawRectangle(Convert(GetRect(RectRange::Margin)), UiManager::GetInstance()->GetPredefineResources()->debug_layout_out_border_brush.Get());
}
#endif
if (is_bordered_ && geometry_info_.border_geometry != nullptr)
device_context->DrawGeometry(
geometry_info_.border_geometry.Get(),
GetBorderProperty().GetBrush().Get(),
GetBorderProperty().GetStrokeWidth(),
GetBorderProperty().GetStrokeStyle().Get()
);
}
void Control::OnDrawCore(ID2D1DeviceContext* device_context)
{
const auto ground_geometry = geometry_info_.padding_content_geometry;
//draw background.
if (ground_geometry != nullptr && background_brush_ != nullptr)
device_context->FillGeometry(ground_geometry.Get(), background_brush_.Get());
const auto padding_rect = GetRect(RectRange::Padding);
graph::WithTransform(device_context, D2D1::Matrix3x2F::Translation(padding_rect.left, padding_rect.top),
[this](ID2D1DeviceContext* device_context)
{
OnDrawBackground(device_context);
DrawEventArgs args(this, this, device_context);
draw_background_event.Raise(args);
});
const auto rect = GetRect(RectRange::Content);
graph::WithTransform(device_context, D2D1::Matrix3x2F::Translation(rect.left, rect.top),
[this](ID2D1DeviceContext* device_context)
{
OnDrawContent(device_context);
DrawEventArgs args(this, this, device_context);
draw_content_event.Raise(args);
});
//draw foreground.
if (ground_geometry != nullptr && foreground_brush_ != nullptr)
device_context->FillGeometry(ground_geometry.Get(), foreground_brush_.Get());
graph::WithTransform(device_context, D2D1::Matrix3x2F::Translation(padding_rect.left, padding_rect.top),
[this](ID2D1DeviceContext* device_context)
{
OnDrawForeground(device_context);
DrawEventArgs args(this, this, device_context);
draw_foreground_event.Raise(args);
});
}
void Control::OnDrawContent(ID2D1DeviceContext * device_context)
{
}
void Control::OnDrawForeground(ID2D1DeviceContext* device_context)
{
}
void Control::OnDrawBackground(ID2D1DeviceContext* device_context)
{
}
void Control::OnPositionChanged(PositionChangedEventArgs & args)
{
}
void Control::OnSizeChanged(SizeChangedEventArgs & args)
{
}
void Control::OnPositionChangedCore(PositionChangedEventArgs & args)
{
}
namespace
{
#ifdef CRU_DEBUG_LAYOUT
Microsoft::WRL::ComPtr<ID2D1Geometry> CalculateSquareRingGeometry(const Rect& out, const Rect& in)
{
const auto d2d1_factory = graph::GraphManager::GetInstance()->GetD2D1Factory();
Microsoft::WRL::ComPtr<ID2D1RectangleGeometry> out_geometry;
ThrowIfFailed(d2d1_factory->CreateRectangleGeometry(Convert(out), &out_geometry));
Microsoft::WRL::ComPtr<ID2D1RectangleGeometry> in_geometry;
ThrowIfFailed(d2d1_factory->CreateRectangleGeometry(Convert(in), &in_geometry));
Microsoft::WRL::ComPtr<ID2D1PathGeometry> result_geometry;
ThrowIfFailed(d2d1_factory->CreatePathGeometry(&result_geometry));
Microsoft::WRL::ComPtr<ID2D1GeometrySink> sink;
ThrowIfFailed(result_geometry->Open(&sink));
ThrowIfFailed(out_geometry->CombineWithGeometry(in_geometry.Get(), D2D1_COMBINE_MODE_EXCLUDE, D2D1::Matrix3x2F::Identity(), sink.Get()));
ThrowIfFailed(sink->Close());
return result_geometry;
}
#endif
}
void Control::OnSizeChangedCore(SizeChangedEventArgs & args)
{
RegenerateGeometryInfo();
#ifdef CRU_DEBUG_LAYOUT
margin_geometry_ = CalculateSquareRingGeometry(GetRect(RectRange::Margin), GetRect(RectRange::FullBorder));
padding_geometry_ = CalculateSquareRingGeometry(GetRect(RectRange::Padding), GetRect(RectRange::Content));
#endif
}
void Control::RaisePositionChangedEvent(PositionChangedEventArgs& args)
{
OnPositionChangedCore(args);
OnPositionChanged(args);
position_changed_event.Raise(args);
}
void Control::RaiseSizeChangedEvent(SizeChangedEventArgs& args)
{
OnSizeChangedCore(args);
OnSizeChanged(args);
size_changed_event.Raise(args);
}
void Control::RegenerateGeometryInfo()
{
if (IsBordered())
{
const auto bound_rect = GetRect(RectRange::HalfBorder);
const auto bound_rounded_rect = D2D1::RoundedRect(Convert(bound_rect),
GetBorderProperty().GetRadiusX(),
GetBorderProperty().GetRadiusY());
Microsoft::WRL::ComPtr<ID2D1RoundedRectangleGeometry> geometry;
ThrowIfFailed(
graph::GraphManager::GetInstance()->GetD2D1Factory()->CreateRoundedRectangleGeometry(bound_rounded_rect, &geometry)
);
geometry_info_.border_geometry = std::move(geometry);
const auto padding_rect = GetRect(RectRange::Padding);
const auto in_border_rounded_rect = D2D1::RoundedRect(Convert(padding_rect),
GetBorderProperty().GetRadiusX() - GetBorderProperty().GetStrokeWidth() / 2.0f,
GetBorderProperty().GetRadiusY() - GetBorderProperty().GetStrokeWidth() / 2.0f);
Microsoft::WRL::ComPtr<ID2D1RoundedRectangleGeometry> geometry2;
ThrowIfFailed(
graph::GraphManager::GetInstance()->GetD2D1Factory()->CreateRoundedRectangleGeometry(in_border_rounded_rect, &geometry2)
);
geometry_info_.padding_content_geometry = geometry2;
Microsoft::WRL::ComPtr<ID2D1RectangleGeometry> geometry3;
ThrowIfFailed(
graph::GraphManager::GetInstance()->GetD2D1Factory()->CreateRectangleGeometry(Convert(GetRect(RectRange::Content)), &geometry3)
);
Microsoft::WRL::ComPtr<ID2D1PathGeometry> geometry4;
ThrowIfFailed(
graph::GraphManager::GetInstance()->GetD2D1Factory()->CreatePathGeometry(&geometry4)
);
Microsoft::WRL::ComPtr<ID2D1GeometrySink> sink;
geometry4->Open(&sink);
ThrowIfFailed(
geometry3->CombineWithGeometry(geometry2.Get(), D2D1_COMBINE_MODE_INTERSECT, D2D1::Matrix3x2F::Identity(), sink.Get())
);
sink->Close();
geometry_info_.content_geometry = std::move(geometry4);
}
else
{
const auto bound_rect = GetRect(RectRange::Padding);
Microsoft::WRL::ComPtr<ID2D1RectangleGeometry> geometry;
ThrowIfFailed(
graph::GraphManager::GetInstance()->GetD2D1Factory()->CreateRectangleGeometry(Convert(bound_rect), &geometry)
);
geometry_info_.border_geometry = geometry;
geometry_info_.padding_content_geometry = std::move(geometry);
Microsoft::WRL::ComPtr<ID2D1RectangleGeometry> geometry2;
ThrowIfFailed(
graph::GraphManager::GetInstance()->GetD2D1Factory()->CreateRectangleGeometry(Convert(GetRect(RectRange::Content)), &geometry2)
);
geometry_info_.content_geometry = std::move(geometry2);
}
}
void Control::OnMouseEnter(MouseEventArgs & args)
{
}
void Control::OnMouseLeave(MouseEventArgs & args)
{
}
void Control::OnMouseMove(MouseEventArgs & args)
{
}
void Control::OnMouseDown(MouseButtonEventArgs & args)
{
}
void Control::OnMouseUp(MouseButtonEventArgs & args)
{
}
void Control::OnMouseClick(MouseButtonEventArgs& args)
{
}
void Control::OnMouseEnterCore(MouseEventArgs & args)
{
is_mouse_inside_ = true;
}
void Control::OnMouseLeaveCore(MouseEventArgs & args)
{
is_mouse_inside_ = false;
for (auto& is_mouse_click_valid : is_mouse_click_valid_map_)
{
if (is_mouse_click_valid.second)
{
is_mouse_click_valid.second = false;
OnMouseClickEnd(is_mouse_click_valid.first);
}
}
}
void Control::OnMouseMoveCore(MouseEventArgs & args)
{
}
void Control::OnMouseDownCore(MouseButtonEventArgs & args)
{
if (is_focus_on_pressed_ && args.GetSender() == args.GetOriginalSender())
RequestFocus();
is_mouse_click_valid_map_[args.GetMouseButton()] = true;
OnMouseClickBegin(args.GetMouseButton());
}
void Control::OnMouseUpCore(MouseButtonEventArgs & args)
{
if (is_mouse_click_valid_map_[args.GetMouseButton()])
{
is_mouse_click_valid_map_[args.GetMouseButton()] = false;
RaiseMouseClickEvent(args);
OnMouseClickEnd(args.GetMouseButton());
}
}
void Control::OnMouseClickCore(MouseButtonEventArgs& args)
{
}
void Control::RaiseMouseEnterEvent(MouseEventArgs& args)
{
OnMouseEnterCore(args);
OnMouseEnter(args);
mouse_enter_event.Raise(args);
}
void Control::RaiseMouseLeaveEvent(MouseEventArgs& args)
{
OnMouseLeaveCore(args);
OnMouseLeave(args);
mouse_leave_event.Raise(args);
}
void Control::RaiseMouseMoveEvent(MouseEventArgs& args)
{
OnMouseMoveCore(args);
OnMouseMove(args);
mouse_move_event.Raise(args);
}
void Control::RaiseMouseDownEvent(MouseButtonEventArgs& args)
{
OnMouseDownCore(args);
OnMouseDown(args);
mouse_down_event.Raise(args);
}
void Control::RaiseMouseUpEvent(MouseButtonEventArgs& args)
{
OnMouseUpCore(args);
OnMouseUp(args);
mouse_up_event.Raise(args);
}
void Control::RaiseMouseClickEvent(MouseButtonEventArgs& args)
{
OnMouseClickCore(args);
OnMouseClick(args);
mouse_click_event.Raise(args);
}
void Control::OnMouseClickBegin(MouseButton button)
{
}
void Control::OnMouseClickEnd(MouseButton button)
{
}
void Control::OnKeyDown(KeyEventArgs& args)
{
}
void Control::OnKeyUp(KeyEventArgs& args)
{
}
void Control::OnChar(CharEventArgs& args)
{
}
void Control::OnKeyDownCore(KeyEventArgs& args)
{
}
void Control::OnKeyUpCore(KeyEventArgs& args)
{
}
void Control::OnCharCore(CharEventArgs& args)
{
}
void Control::RaiseKeyDownEvent(KeyEventArgs& args)
{
OnKeyDownCore(args);
OnKeyDown(args);
key_down_event.Raise(args);
}
void Control::RaiseKeyUpEvent(KeyEventArgs& args)
{
OnKeyUpCore(args);
OnKeyUp(args);
key_up_event.Raise(args);
}
void Control::RaiseCharEvent(CharEventArgs& args)
{
OnCharCore(args);
OnChar(args);
char_event.Raise(args);
}
void Control::OnGetFocus(FocusChangeEventArgs& args)
{
}
void Control::OnLoseFocus(FocusChangeEventArgs& args)
{
}
void Control::OnGetFocusCore(FocusChangeEventArgs& args)
{
}
void Control::OnLoseFocusCore(FocusChangeEventArgs& args)
{
}
void Control::RaiseGetFocusEvent(FocusChangeEventArgs& args)
{
OnGetFocusCore(args);
OnGetFocus(args);
get_focus_event.Raise(args);
}
void Control::RaiseLoseFocusEvent(FocusChangeEventArgs& args)
{
OnLoseFocusCore(args);
OnLoseFocus(args);
lose_focus_event.Raise(args);
}
inline Size ThicknessToSize(const Thickness& thickness)
{
return Size(thickness.left + thickness.right, thickness.top + thickness.bottom);
}
inline float AtLeast0(const float value)
{
return value < 0 ? 0 : value;
}
Size Control::OnMeasureCore(const Size& available_size)
{
const auto layout_params = GetLayoutParams();
if (!layout_params->Validate())
throw std::runtime_error("LayoutParams is not valid. Please check it.");
auto border_size = Size::Zero();
if (is_bordered_)
{
const auto border_width = GetBorderProperty().GetStrokeWidth();
border_size = Size(border_width * 2.0f, border_width * 2.0f);
}
// the total size of padding, border and margin
const auto outer_size = ThicknessToSize(layout_params->padding) +
ThicknessToSize(layout_params->margin) + border_size;
auto&& get_content_measure_length = [](const LayoutSideParams& layout_length, const float available_length, const float outer_length) -> float
{
float length;
if (layout_length.mode == MeasureMode::Exactly)
length = layout_length.length;
else if (available_length > outer_length)
length = available_length - outer_length;
else
length = 0;
return Coerce(length, layout_length.min, layout_length.max);
};
// if padding, margin and border exceeded, then content size is 0.
const auto content_measure_size = Size(
get_content_measure_length(layout_params->width, available_size.width, outer_size.width),
get_content_measure_length(layout_params->height, available_size.height, outer_size.height)
);
const auto content_actual_size = OnMeasureContent(content_measure_size);
auto stretch_width = false;
auto stretch_width_determined = true;
auto stretch_height = false;
auto stretch_height_determined = true;
// if it is stretch, init is stretch, and undetermined.
if (layout_params->width.mode == MeasureMode::Stretch)
{
stretch_width = true;
stretch_width_determined = false;
}
if (layout_params->height.mode == MeasureMode::Stretch)
{
stretch_height = true;
stretch_width_determined = false;
}
if (!stretch_width_determined || !stretch_height_determined)
{
auto parent = GetParent();
while (parent != nullptr)
{
const auto lp = parent->GetLayoutParams();
if (!stretch_width_determined)
{
if (lp->width.mode == MeasureMode::Content) // if the first ancestor that is not stretch is content, then it can't stretch.
{
stretch_width = false;
stretch_width_determined = true;
}
if (lp->width.mode == MeasureMode::Exactly) // if the first ancestor that is not stretch is content, then it must be stretch.
{
stretch_width = true;
stretch_width_determined = true;
}
}
if (!stretch_height_determined) // the same as width
{
if (lp->height.mode == MeasureMode::Content) // if the first ancestor that is not stretch is content, then it can't stretch.
{
stretch_height = false;
stretch_height_determined = true;
}
if (lp->height.mode == MeasureMode::Exactly) // if the first ancestor that is not stretch is content, then it must be stretch.
{
stretch_height = true;
stretch_height_determined = true;
}
}
if (stretch_width_determined && stretch_height_determined) // if both are determined.
break;
parent = GetParent();
}
}
auto&& calculate_final_length = [](const bool stretch, const std::optional<float> min_length, const float measure_length, const float actual_length) -> float
{
// only use measure length when stretch and actual length is smaller than measure length, that is "stretch"
if (stretch && actual_length < measure_length)
return measure_length;
return Coerce(actual_length, min_length, std::nullopt);
};
const auto final_size = Size(
calculate_final_length(stretch_width, layout_params->width.min, content_measure_size.width, content_actual_size.width),
calculate_final_length(stretch_height, layout_params->height.min, content_measure_size.height, content_actual_size.height)
) + outer_size;
return final_size;
}
void Control::OnLayoutCore(const Rect& rect)
{
const auto layout_params = GetLayoutParams();
auto border_width = 0.0f;
if (is_bordered_)
{
border_width = GetBorderProperty().GetStrokeWidth();
}
const Rect content_rect(
rect.left + layout_params->padding.left + layout_params->margin.right + border_width,
rect.top + layout_params->padding.top + layout_params->margin.top + border_width,
rect.width - layout_params->padding.GetHorizontalTotal() - layout_params->margin.GetHorizontalTotal() - border_width * 2.0f,
rect.height - layout_params->padding.GetVerticalTotal() - layout_params->margin.GetVerticalTotal() - border_width * 2.0f
);
if (content_rect.width < 0.0)
throw std::runtime_error(Format("Width to layout must sufficient. But in {}, width for content is {}.", ToUtf8String(GetControlType()), content_rect.width));
if (content_rect.height < 0.0)
throw std::runtime_error(Format("Height to layout must sufficient. But in {}, height for content is {}.", ToUtf8String(GetControlType()), content_rect.height));
OnLayoutContent(content_rect);
}
Size Control::OnMeasureContent(const Size& available_size)
{
auto max_child_size = Size::Zero();
for (auto control: GetChildren())
{
control->Measure(available_size);
const auto&& size = control->GetDesiredSize();
if (max_child_size.width < size.width)
max_child_size.width = size.width;
if (max_child_size.height < size.height)
max_child_size.height = size.height;
}
// coerce size fro stretch.
for (auto control: GetChildren())
{
auto size = control->GetDesiredSize();
const auto layout_params = control->GetLayoutParams();
if (layout_params->width.mode == MeasureMode::Stretch)
size.width = max_child_size.width;
if (layout_params->height.mode == MeasureMode::Stretch)
size.height = max_child_size.height;
control->SetDesiredSize(size);
}
return max_child_size;
}
void Control::OnLayoutContent(const Rect& rect)
{
for (auto control: GetChildren())
{
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(rect.left, layout_params->width.alignment, rect.width, size.width),
calculate_anchor(rect.top, layout_params->height.alignment, rect.height, size.height)
), size));
}
}
void Control::AfterLayoutSelf()
{
}
void Control::CheckAndNotifyPositionChanged()
{
if (this->old_position_ != this->position_)
{
PositionChangedEventArgs args(this, this, this->old_position_, this->position_);
this->RaisePositionChangedEvent(args);
this->old_position_ = this->position_;
}
}
std::list<Control*> GetAncestorList(Control* control)
{
std::list<Control*> l;
while (control != nullptr)
{
l.push_front(control);
control = control->GetParent();
}
return l;
}
Control* FindLowestCommonAncestor(Control * left, Control * right)
{
if (left == nullptr || right == nullptr)
return nullptr;
auto&& left_list = GetAncestorList(left);
auto&& right_list = GetAncestorList(right);
// the root is different
if (left_list.front() != right_list.front())
return nullptr;
// find the last same control or the last control (one is ancestor of the other)
auto left_i = left_list.cbegin();
auto right_i = right_list.cbegin();
while (true)
{
if (left_i == left_list.cend())
return *(--left_i);
if (right_i == right_list.cend())
return *(--right_i);
if (*left_i != *right_i)
return *(--left_i);
++left_i;
++right_i;
}
}
Control * IsAncestorOrDescendant(Control * left, Control * right)
{
//Search up along the trunk from "left". Return if find "right".
auto control = left;
while (control != nullptr)
{
if (control == right)
return control;
control = control->GetParent();
}
//Search up along the trunk from "right". Return if find "left".
control = right;
while (control != nullptr)
{
if (control == left)
return control;
control = control->GetParent();
}
return nullptr;
}
}
|