From 5729a5aa1b443e3e25f3e14dee29636d3b31a6f8 Mon Sep 17 00:00:00 2001 From: crupest Date: Sun, 18 Oct 2020 21:09:21 +0800 Subject: ... --- demos/main/main.cpp | 34 +++++++++++----------------------- 1 file changed, 11 insertions(+), 23 deletions(-) (limited to 'demos/main/main.cpp') diff --git a/demos/main/main.cpp b/demos/main/main.cpp index 82038731..3026baeb 100644 --- a/demos/main/main.cpp +++ b/demos/main/main.cpp @@ -1,6 +1,7 @@ #include "cru/platform/HeapDebug.hpp" #include "cru/platform/native/UiApplication.hpp" #include "cru/platform/native/Window.hpp" +#include "cru/ui/Base.hpp" #include "cru/ui/UiHost.hpp" #include "cru/ui/Window.hpp" #include "cru/ui/controls/Button.hpp" @@ -10,12 +11,9 @@ #include "cru/ui/controls/TextBox.hpp" using cru::platform::native::CreateUiApplication; -using cru::ui::Rect; -using cru::ui::Thickness; using cru::ui::Window; using cru::ui::controls::Button; using cru::ui::controls::FlexLayout; -using cru::ui::controls::StackLayout; using cru::ui::controls::TextBlock; using cru::ui::controls::TextBox; @@ -31,30 +29,20 @@ int main() { const auto flex_layout = FlexLayout::Create(); window->SetChild(flex_layout); + flex_layout->SetFlexDirection(cru::ui::FlexDirection::Vertical); - const auto button = Button::Create(); - const auto text_block1 = TextBlock::Create(); - text_block1->SetText(u"Hello World!"); - button->SetChild(text_block1); - flex_layout->AddChild(button, 0); - - const auto text_block2 = TextBlock::Create(); - text_block2->SetText(u"Hello World!"); - - const auto text_block3 = TextBlock::Create(); - text_block3->SetText(u"Overlapped text"); + const auto text_block = TextBlock::Create(); + text_block->SetText(u"Hello World from CruUI!"); + flex_layout->AddChild(text_block, 0); - const auto stack_layout = StackLayout::Create(); - stack_layout->AddChild(text_block2, 0); - stack_layout->AddChild(text_block3, 1); - flex_layout->AddChild(stack_layout, 1); - - const auto text_block4 = TextBlock::Create(); - text_block4->SetText(u"Hello World!!!"); - flex_layout->AddChild(text_block4, 2); + const auto button_text_block = TextBlock::Create(); + button_text_block->SetText(u"OK"); + const auto button = Button::Create(); + button->SetChild(button_text_block); + flex_layout->AddChild(button, 1); const auto text_box = TextBox::Create(); - flex_layout->AddChild(text_box, 3); + flex_layout->AddChild(text_box, 2); window->GetUiHost()->GetNativeWindowResolver()->Resolve()->SetVisible(true); -- cgit v1.2.3 From c072432e68d7a3d7659add0994b2f8caf387ddf2 Mon Sep 17 00:00:00 2001 From: crupest Date: Sun, 18 Oct 2020 21:28:35 +0800 Subject: ... --- demos/main/main.cpp | 5 +++-- include/cru/platform/GraphBase.hpp | 4 ++++ include/cru/ui/controls/FlexLayout.hpp | 3 +++ src/ui/controls/FlexLayout.cpp | 9 +++++++++ src/ui/render/FlexLayoutRenderObject.cpp | 15 ++++++++------- src/ui/render/RenderObject.cpp | 4 ++++ 6 files changed, 31 insertions(+), 9 deletions(-) (limited to 'demos/main/main.cpp') diff --git a/demos/main/main.cpp b/demos/main/main.cpp index 3026baeb..10b43b0f 100644 --- a/demos/main/main.cpp +++ b/demos/main/main.cpp @@ -6,7 +6,6 @@ #include "cru/ui/Window.hpp" #include "cru/ui/controls/Button.hpp" #include "cru/ui/controls/FlexLayout.hpp" -#include "cru/ui/controls/StackLayout.hpp" #include "cru/ui/controls/TextBlock.hpp" #include "cru/ui/controls/TextBox.hpp" @@ -27,9 +26,11 @@ int main() { const auto window = Window::CreateOverlapped(); const auto flex_layout = FlexLayout::Create(); + flex_layout->SetFlexDirection(cru::ui::FlexDirection::Vertical); + flex_layout->SetContentMainAlign(cru::ui::FlexCrossAlignment::Center); + flex_layout->SetItemCrossAlign(cru::ui::FlexCrossAlignment::Center); window->SetChild(flex_layout); - flex_layout->SetFlexDirection(cru::ui::FlexDirection::Vertical); const auto text_block = TextBlock::Create(); text_block->SetText(u"Hello World from CruUI!"); diff --git a/include/cru/platform/GraphBase.hpp b/include/cru/platform/GraphBase.hpp index 571b36f7..6700765e 100644 --- a/include/cru/platform/GraphBase.hpp +++ b/include/cru/platform/GraphBase.hpp @@ -18,6 +18,10 @@ struct Point final { constexpr Point(const float x, const float y) : x(x), y(y) {} explicit constexpr Point(const Size& size); + std::u16string ToDebugString() const { + return fmt::format(u"({}, {})", ToUtf16String(x), ToUtf16String(y)); + } + float x = 0; float y = 0; }; diff --git a/include/cru/ui/controls/FlexLayout.hpp b/include/cru/ui/controls/FlexLayout.hpp index 87162569..0ffedba5 100644 --- a/include/cru/ui/controls/FlexLayout.hpp +++ b/include/cru/ui/controls/FlexLayout.hpp @@ -28,6 +28,9 @@ class FlexLayout : public LayoutControl { FlexDirection GetFlexDirection() const; void SetFlexDirection(FlexDirection direction); + FlexCrossAlignment GetItemCrossAlign() const; + void SetItemCrossAlign(FlexCrossAlignment alignment); + FlexChildLayoutData GetChildLayoutData(Control* control); void SetChildLayoutData(Control* control, FlexChildLayoutData data); diff --git a/src/ui/controls/FlexLayout.cpp b/src/ui/controls/FlexLayout.cpp index b7f350dc..05f6999f 100644 --- a/src/ui/controls/FlexLayout.cpp +++ b/src/ui/controls/FlexLayout.cpp @@ -60,6 +60,15 @@ void FlexLayout::SetFlexDirection(FlexDirection direction) { render_object_->SetFlexDirection(direction); } +FlexCrossAlignment FlexLayout::GetItemCrossAlign() const { + return render_object_->GetItemCrossAlign(); +} + +void FlexLayout::SetItemCrossAlign(FlexCrossAlignment alignment) { + if (alignment == GetItemCrossAlign()) return; + render_object_->SetItemCrossAlign(alignment); +} + void FlexLayout::OnAddChild(Control* child, const Index position) { render_object_->AddChild(child->GetRenderObject(), position); } diff --git a/src/ui/render/FlexLayoutRenderObject.cpp b/src/ui/render/FlexLayoutRenderObject.cpp index 1c39cc8f..36a2dcea 100644 --- a/src/ui/render/FlexLayoutRenderObject.cpp +++ b/src/ui/render/FlexLayoutRenderObject.cpp @@ -391,10 +391,11 @@ void FlexLayoutRenderObject::OnLayoutContent(const Rect& content_rect) { const auto cross_align = GetChildLayoutDataList()[i].cross_alignment.value_or( GetItemCrossAlign()); - child->Layout( - Point{content_rect.top + current_main_offset, - CalculateAnchorByAlignment(cross_align, content_rect.left, - content_rect.width, size.width)}); + child->Layout(Point{ + CalculateAnchorByAlignment(cross_align, content_rect.left, + content_rect.width, size.width), + content_rect.top + current_main_offset, + }); current_main_offset += size.height; } } else { @@ -406,9 +407,9 @@ void FlexLayoutRenderObject::OnLayoutContent(const Rect& content_rect) { GetChildLayoutDataList()[i].cross_alignment.value_or( GetItemCrossAlign()); child->Layout( - Point{content_rect.GetBottom() - current_main_offset, - CalculateAnchorByAlignment(cross_align, content_rect.left, - content_rect.width, size.width)}); + Point{CalculateAnchorByAlignment(cross_align, content_rect.left, + content_rect.width, size.width), + content_rect.GetBottom() - current_main_offset}); current_main_offset += size.height; } } diff --git a/src/ui/render/RenderObject.cpp b/src/ui/render/RenderObject.cpp index bc2228d3..57116f93 100644 --- a/src/ui/render/RenderObject.cpp +++ b/src/ui/render/RenderObject.cpp @@ -88,6 +88,10 @@ void RenderObject::Measure(const MeasureRequirement& requirement, } void RenderObject::Layout(const Point& offset) { +#if CRUUI_DEBUG_LAYOUT + log::Debug(u"{} Layout :\noffset: {}", this->GetDebugPathInTree(), + offset.ToDebugString()); +#endif offset_ = offset; OnLayoutCore(); } -- cgit v1.2.3 From 6ce70ed4b08c7db20b6b384be26c7fc4e11c98de Mon Sep 17 00:00:00 2001 From: crupest Date: Wed, 28 Oct 2020 20:51:55 +0800 Subject: ... --- demos/main/main.cpp | 4 +- include/cru/ui/Base.hpp | 2 +- include/cru/ui/Control.hpp | 12 +- include/cru/ui/UiHost.hpp | 185 ------------ include/cru/ui/Window.hpp | 6 +- include/cru/ui/WindowHost.hpp | 185 ++++++++++++ include/cru/ui/render/RenderObject.hpp | 6 +- include/cru/ui/render/WindowRenderObject.hpp | 2 +- src/ui/CMakeLists.txt | 4 +- src/ui/ContentControl.cpp | 6 +- src/ui/Control.cpp | 20 +- src/ui/LayoutControl.cpp | 4 +- src/ui/UiHost.cpp | 416 -------------------------- src/ui/Window.cpp | 4 +- src/ui/WindowHost.cpp | 418 +++++++++++++++++++++++++++ src/ui/controls/TextControlService.hpp | 6 +- src/ui/render/RenderObject.cpp | 6 +- src/ui/render/WindowRenderObject.cpp | 4 +- 18 files changed, 646 insertions(+), 644 deletions(-) delete mode 100644 include/cru/ui/UiHost.hpp create mode 100644 include/cru/ui/WindowHost.hpp delete mode 100644 src/ui/UiHost.cpp create mode 100644 src/ui/WindowHost.cpp (limited to 'demos/main/main.cpp') diff --git a/demos/main/main.cpp b/demos/main/main.cpp index 10b43b0f..f7635231 100644 --- a/demos/main/main.cpp +++ b/demos/main/main.cpp @@ -2,7 +2,7 @@ #include "cru/platform/native/UiApplication.hpp" #include "cru/platform/native/Window.hpp" #include "cru/ui/Base.hpp" -#include "cru/ui/UiHost.hpp" +#include "cru/ui/WindowHost.hpp" #include "cru/ui/Window.hpp" #include "cru/ui/controls/Button.hpp" #include "cru/ui/controls/FlexLayout.hpp" @@ -45,7 +45,7 @@ int main() { const auto text_box = TextBox::Create(); flex_layout->AddChild(text_box, 2); - window->GetUiHost()->GetNativeWindowResolver()->Resolve()->SetVisible(true); + window->GetWindowHost()->GetNativeWindowResolver()->Resolve()->SetVisible(true); return application->Run(); } diff --git a/include/cru/ui/Base.hpp b/include/cru/ui/Base.hpp index 6be359ab..dd93f187 100644 --- a/include/cru/ui/Base.hpp +++ b/include/cru/ui/Base.hpp @@ -29,7 +29,7 @@ namespace colors = cru::platform::colors; class Window; class Control; class ClickDetector; -class UiHost; +class WindowHost; namespace render { class RenderObject; diff --git a/include/cru/ui/Control.hpp b/include/cru/ui/Control.hpp index bd86bc2f..692dcc9b 100644 --- a/include/cru/ui/Control.hpp +++ b/include/cru/ui/Control.hpp @@ -9,7 +9,7 @@ namespace cru::ui { class Control : public Object { - friend UiHost; + friend WindowHost; protected: Control(); @@ -27,7 +27,7 @@ class Control : public Object { //*************** region: tree *************** public: // Get the ui host if attached, otherwise, return nullptr. - UiHost* GetUiHost() const { return ui_host_; } + WindowHost* GetWindowHost() const { return ui_host_; } Control* GetParent() const { return parent_; } @@ -37,7 +37,7 @@ class Control : public Object { void TraverseDescendants(const std::function& predicate); void _SetParent(Control* parent); - void _SetDescendantUiHost(UiHost* host); + void _SetDescendantWindowHost(WindowHost* host); private: static void _TraverseDescendants( @@ -135,13 +135,13 @@ class Control : public Object { //*************** region: tree *************** protected: virtual void OnParentChanged(Control* old_parent, Control* new_parent); - virtual void OnAttachToHost(UiHost* host); - virtual void OnDetachFromHost(UiHost* host); + virtual void OnAttachToHost(WindowHost* host); + virtual void OnDetachFromHost(WindowHost* host); virtual void OnMouseHoverChange(bool newHover) { CRU_UNUSED(newHover) } private: - UiHost* ui_host_ = nullptr; + WindowHost* ui_host_ = nullptr; Control* parent_ = nullptr; private: diff --git a/include/cru/ui/UiHost.hpp b/include/cru/ui/UiHost.hpp deleted file mode 100644 index 2437b967..00000000 --- a/include/cru/ui/UiHost.hpp +++ /dev/null @@ -1,185 +0,0 @@ -#pragma once -#include -#include "Base.hpp" - -#include "cru/common/Event.hpp" -#include "cru/common/SelfResolvable.hpp" -#include "render/Base.hpp" - -namespace cru::ui { -struct AfterLayoutEventArgs {}; - -// The host of all controls and render objects. -// -// 3 situations on destroy: -// 1. Native window destroyed, IsRetainAfterDestroy: false: -// OnNativeDestroy(set native_window_destroyed_ to true, call ~Window due to -// deleting_ is false and IsRetainAfterDestroy is false) -> ~Window -> -// ~UiHost(not destroy native window repeatedly due to native_window_destroyed_ -// is true) -// 2. Native window destroyed, IsRetainAfterDestroy: true: -// OnNativeDestroy(set native_window_destroyed_ to true, not call ~Window -// because deleting_ is false and IsRetainAfterDestroy is true) -// then, ~Window -> ~UiHost(not destroy native window repeatedly due to -// native_window_destroyed_ is true) -// 3. Native window not destroyed, ~Window is called: -// ~Window -> ~UiHost(set deleting_ to true, destroy native window -// due to native_window_destroyed is false) -> OnNativeDestroy(not call ~Window -// due to deleting_ is true and IsRetainAfterDestroy is whatever) -// In conclusion: -// 1. Set native_window_destroyed_ to true at the beginning of OnNativeDestroy. -// 2. Set deleting_ to true at the beginning of ~UiHost. -// 3. Destroy native window when native_window_destroy_ is false in ~Window. -// 4. Delete Window when deleting_ is false and IsRetainAfterDestroy is false in -// OnNativeDestroy. -class UiHost : public Object, public SelfResolvable { - CRU_DEFINE_CLASS_LOG_TAG(u"cru::ui::UiHost") - - public: - // This will create root window render object and attach it to window. - // It will also create and manage a native window. - UiHost(Window* window); - - CRU_DELETE_COPY(UiHost) - CRU_DELETE_MOVE(UiHost) - - ~UiHost() override; - - public: - // Mark the layout as invalid, and arrange a re-layout later. - // This method could be called more than one times in a message cycle. But - // layout only takes place once. - void InvalidateLayout(); - - // Mark the paint as invalid, and arrange a re-paint later. - // This method could be called more than one times in a message cycle. But - // paint only takes place once. - void InvalidatePaint(); - - IEvent* AfterLayoutEvent() { - return &after_layout_event_; - } - - // If true, preferred size of root render object is set to window size when - // measure. Default is true. - bool IsLayoutPreferToFillWindow() const; - void SetLayoutPreferToFillWindow(bool value); - - void Relayout(); - - // Get current control that mouse hovers on. This ignores the mouse-capture - // control. Even when mouse is captured by another control, this function - // return the control under cursor. You can use `GetMouseCaptureControl` to - // get more info. - Control* GetMouseHoverControl() const { return mouse_hover_control_; } - - //*************** region: focus *************** - - // Request focus for specified control. - bool RequestFocusFor(Control* control); - - // Get the control that has focus. - Control* GetFocusControl(); - - //*************** region: focus *************** - - // Pass nullptr to release capture. If mouse is already capture by a control, - // this capture will fail and return false. If control is identical to the - // capturing control, capture is not changed and this function will return - // true. - // - // When capturing control changes, - // appropriate event will be sent. If mouse is not on the capturing control - // and capture is released, mouse enter event will be sent to the mouse-hover - // control. If mouse is not on the capturing control and capture is set, mouse - // leave event will be sent to the mouse-hover control. - bool CaptureMouseFor(Control* control); - - // Return null if not captured. - Control* GetMouseCaptureControl(); - - Control* HitTest(const Point& point); - - void UpdateCursor(); - - std::shared_ptr - GetNativeWindowResolver() { - return native_window_resolver_; - } - - bool IsRetainAfterDestroy() { return retain_after_destroy_; } - - void SetRetainAfterDestroy(bool destroy) { retain_after_destroy_ = destroy; } - - // Is layout is invalid, wait for relayout and then run the action. Otherwist - // run it right now. - void RunAfterLayoutStable(std::function action); - - private: - //*************** region: native messages *************** - void OnNativeDestroy(platform::native::INativeWindow* window, std::nullptr_t); - void OnNativePaint(platform::native::INativeWindow* window, std::nullptr_t); - void OnNativeResize(platform::native::INativeWindow* window, - const Size& size); - - void OnNativeFocus(platform::native::INativeWindow* window, - cru::platform::native::FocusChangeType focus); - - void OnNativeMouseEnterLeave( - platform::native::INativeWindow* window, - cru::platform::native::MouseEnterLeaveType enter); - void OnNativeMouseMove(platform::native::INativeWindow* window, - const Point& point); - void OnNativeMouseDown( - platform::native::INativeWindow* window, - const platform::native::NativeMouseButtonEventArgs& args); - void OnNativeMouseUp( - platform::native::INativeWindow* window, - const platform::native::NativeMouseButtonEventArgs& args); - - void OnNativeKeyDown(platform::native::INativeWindow* window, - const platform::native::NativeKeyEventArgs& args); - void OnNativeKeyUp(platform::native::INativeWindow* window, - const platform::native::NativeKeyEventArgs& args); - - //*************** region: event dispatcher helper *************** - - void DispatchMouseHoverControlChangeEvent(Control* old_control, - Control* new_control, - const Point& point, bool no_leave, - bool no_enter); - - private: - bool need_layout_ = false; - - Event after_layout_event_; - std::vector > after_layout_stable_action_; - - std::shared_ptr - native_window_resolver_; - - // See remarks of UiHost. - bool retain_after_destroy_ = false; - // See remarks of UiHost. - bool deleting_ = false; - - // We need this because calling Resolve on resolver in handler of destroy - // event is bad and will always get the dying window. But we need to label the - // window as destroyed so the destructor will not destroy native window - // repeatedly. See remarks of UiHost. - bool native_window_destroyed_ = false; - - std::vector event_revoker_guards_; - - Window* window_control_; - std::unique_ptr root_render_object_; - - Control* mouse_hover_control_; - - Control* focus_control_; // "focus_control_" can't be nullptr - - Control* mouse_captured_control_; - - bool layout_prefer_to_fill_window_ = true; -}; -} // namespace cru::ui diff --git a/include/cru/ui/Window.hpp b/include/cru/ui/Window.hpp index 450ea97b..5ea24855 100644 --- a/include/cru/ui/Window.hpp +++ b/include/cru/ui/Window.hpp @@ -3,7 +3,7 @@ namespace cru::ui { class Window final : public ContentControl { - friend UiHost; + friend WindowHost; public: static constexpr std::u16string_view control_type = u"Window"; @@ -32,9 +32,9 @@ class Window final : public ContentControl { void OnChildChanged(Control* old_child, Control* new_child) override; private: - std::unique_ptr managed_ui_host_; + std::unique_ptr managed_ui_host_; - // UiHost is responsible to take care of lifetime of this. + // WindowHost is responsible to take care of lifetime of this. render::WindowRenderObject* render_object_; }; } // namespace cru::ui diff --git a/include/cru/ui/WindowHost.hpp b/include/cru/ui/WindowHost.hpp new file mode 100644 index 00000000..64116590 --- /dev/null +++ b/include/cru/ui/WindowHost.hpp @@ -0,0 +1,185 @@ +#pragma once +#include +#include "Base.hpp" + +#include "cru/common/Event.hpp" +#include "cru/common/SelfResolvable.hpp" +#include "render/Base.hpp" + +namespace cru::ui { +struct AfterLayoutEventArgs {}; + +// The host of all controls and render objects. +// +// 3 situations on destroy: +// 1. Native window destroyed, IsRetainAfterDestroy: false: +// OnNativeDestroy(set native_window_destroyed_ to true, call ~Window due to +// deleting_ is false and IsRetainAfterDestroy is false) -> ~Window -> +// ~WindowHost(not destroy native window repeatedly due to native_window_destroyed_ +// is true) +// 2. Native window destroyed, IsRetainAfterDestroy: true: +// OnNativeDestroy(set native_window_destroyed_ to true, not call ~Window +// because deleting_ is false and IsRetainAfterDestroy is true) +// then, ~Window -> ~WindowHost(not destroy native window repeatedly due to +// native_window_destroyed_ is true) +// 3. Native window not destroyed, ~Window is called: +// ~Window -> ~WindowHost(set deleting_ to true, destroy native window +// due to native_window_destroyed is false) -> OnNativeDestroy(not call ~Window +// due to deleting_ is true and IsRetainAfterDestroy is whatever) +// In conclusion: +// 1. Set native_window_destroyed_ to true at the beginning of OnNativeDestroy. +// 2. Set deleting_ to true at the beginning of ~WindowHost. +// 3. Destroy native window when native_window_destroy_ is false in ~Window. +// 4. Delete Window when deleting_ is false and IsRetainAfterDestroy is false in +// OnNativeDestroy. +class WindowHost : public Object, public SelfResolvable { + CRU_DEFINE_CLASS_LOG_TAG(u"cru::ui::WindowHost") + + public: + // This will create root window render object and attach it to window. + // It will also create and manage a native window. + WindowHost(Window* window); + + CRU_DELETE_COPY(WindowHost) + CRU_DELETE_MOVE(WindowHost) + + ~WindowHost() override; + + public: + // Mark the layout as invalid, and arrange a re-layout later. + // This method could be called more than one times in a message cycle. But + // layout only takes place once. + void InvalidateLayout(); + + // Mark the paint as invalid, and arrange a re-paint later. + // This method could be called more than one times in a message cycle. But + // paint only takes place once. + void InvalidatePaint(); + + IEvent* AfterLayoutEvent() { + return &after_layout_event_; + } + + // If true, preferred size of root render object is set to window size when + // measure. Default is true. + bool IsLayoutPreferToFillWindow() const; + void SetLayoutPreferToFillWindow(bool value); + + void Relayout(); + + // Get current control that mouse hovers on. This ignores the mouse-capture + // control. Even when mouse is captured by another control, this function + // return the control under cursor. You can use `GetMouseCaptureControl` to + // get more info. + Control* GetMouseHoverControl() const { return mouse_hover_control_; } + + //*************** region: focus *************** + + // Request focus for specified control. + bool RequestFocusFor(Control* control); + + // Get the control that has focus. + Control* GetFocusControl(); + + //*************** region: focus *************** + + // Pass nullptr to release capture. If mouse is already capture by a control, + // this capture will fail and return false. If control is identical to the + // capturing control, capture is not changed and this function will return + // true. + // + // When capturing control changes, + // appropriate event will be sent. If mouse is not on the capturing control + // and capture is released, mouse enter event will be sent to the mouse-hover + // control. If mouse is not on the capturing control and capture is set, mouse + // leave event will be sent to the mouse-hover control. + bool CaptureMouseFor(Control* control); + + // Return null if not captured. + Control* GetMouseCaptureControl(); + + Control* HitTest(const Point& point); + + void UpdateCursor(); + + std::shared_ptr + GetNativeWindowResolver() { + return native_window_resolver_; + } + + bool IsRetainAfterDestroy() { return retain_after_destroy_; } + + void SetRetainAfterDestroy(bool destroy) { retain_after_destroy_ = destroy; } + + // Is layout is invalid, wait for relayout and then run the action. Otherwist + // run it right now. + void RunAfterLayoutStable(std::function action); + + private: + //*************** region: native messages *************** + void OnNativeDestroy(platform::native::INativeWindow* window, std::nullptr_t); + void OnNativePaint(platform::native::INativeWindow* window, std::nullptr_t); + void OnNativeResize(platform::native::INativeWindow* window, + const Size& size); + + void OnNativeFocus(platform::native::INativeWindow* window, + cru::platform::native::FocusChangeType focus); + + void OnNativeMouseEnterLeave( + platform::native::INativeWindow* window, + cru::platform::native::MouseEnterLeaveType enter); + void OnNativeMouseMove(platform::native::INativeWindow* window, + const Point& point); + void OnNativeMouseDown( + platform::native::INativeWindow* window, + const platform::native::NativeMouseButtonEventArgs& args); + void OnNativeMouseUp( + platform::native::INativeWindow* window, + const platform::native::NativeMouseButtonEventArgs& args); + + void OnNativeKeyDown(platform::native::INativeWindow* window, + const platform::native::NativeKeyEventArgs& args); + void OnNativeKeyUp(platform::native::INativeWindow* window, + const platform::native::NativeKeyEventArgs& args); + + //*************** region: event dispatcher helper *************** + + void DispatchMouseHoverControlChangeEvent(Control* old_control, + Control* new_control, + const Point& point, bool no_leave, + bool no_enter); + + private: + bool need_layout_ = false; + + Event after_layout_event_; + std::vector > after_layout_stable_action_; + + std::shared_ptr + native_window_resolver_; + + // See remarks of WindowHost. + bool retain_after_destroy_ = false; + // See remarks of WindowHost. + bool deleting_ = false; + + // We need this because calling Resolve on resolver in handler of destroy + // event is bad and will always get the dying window. But we need to label the + // window as destroyed so the destructor will not destroy native window + // repeatedly. See remarks of WindowHost. + bool native_window_destroyed_ = false; + + std::vector event_revoker_guards_; + + Window* window_control_; + std::unique_ptr root_render_object_; + + Control* mouse_hover_control_; + + Control* focus_control_; // "focus_control_" can't be nullptr + + Control* mouse_captured_control_; + + bool layout_prefer_to_fill_window_ = true; +}; +} // namespace cru::ui diff --git a/include/cru/ui/render/RenderObject.hpp b/include/cru/ui/render/RenderObject.hpp index 57251e3a..f052221e 100644 --- a/include/cru/ui/render/RenderObject.hpp +++ b/include/cru/ui/render/RenderObject.hpp @@ -64,7 +64,7 @@ class RenderObject : public Object { Control* GetAttachedControl() const { return control_; } void SetAttachedControl(Control* new_control) { control_ = new_control; } - UiHost* GetUiHost() const { return ui_host_; } + WindowHost* GetWindowHost() const { return ui_host_; } RenderObject* GetParent() const { return parent_; } @@ -198,11 +198,11 @@ class RenderObject : public Object { private: void SetParent(RenderObject* new_parent); - void SetRenderHostRecursive(UiHost* host); + void SetRenderHostRecursive(WindowHost* host); private: Control* control_ = nullptr; - UiHost* ui_host_ = nullptr; + WindowHost* ui_host_ = nullptr; RenderObject* parent_ = nullptr; std::vector children_{}; diff --git a/include/cru/ui/render/WindowRenderObject.hpp b/include/cru/ui/render/WindowRenderObject.hpp index d2ca5526..23fd8748 100644 --- a/include/cru/ui/render/WindowRenderObject.hpp +++ b/include/cru/ui/render/WindowRenderObject.hpp @@ -6,7 +6,7 @@ namespace cru::ui::render { class WindowRenderObject : public RenderObject { public: - WindowRenderObject(UiHost* host); + WindowRenderObject(WindowHost* host); WindowRenderObject(const WindowRenderObject& other) = delete; WindowRenderObject(WindowRenderObject&& other) = delete; WindowRenderObject& operator=(const WindowRenderObject& other) = delete; diff --git a/src/ui/CMakeLists.txt b/src/ui/CMakeLists.txt index a83ab1d7..d59fd7da 100644 --- a/src/ui/CMakeLists.txt +++ b/src/ui/CMakeLists.txt @@ -12,9 +12,9 @@ add_library(cru_ui STATIC NoChildControl.cpp ShortcutHub.cpp UiEvent.cpp - UiHost.cpp UiManager.cpp Window.cpp + WindowHost.cpp controls/Button.cpp controls/Container.cpp controls/FlexLayout.cpp @@ -42,9 +42,9 @@ target_sources(cru_ui PUBLIC ${CRU_UI_INCLUDE_DIR}/NoChildControl.hpp ${CRU_UI_INCLUDE_DIR}/ShortcutHub.hpp ${CRU_UI_INCLUDE_DIR}/UiEvent.hpp - ${CRU_UI_INCLUDE_DIR}/UiHost.hpp ${CRU_UI_INCLUDE_DIR}/UiManager.hpp ${CRU_UI_INCLUDE_DIR}/Window.hpp + ${CRU_UI_INCLUDE_DIR}/WindowHost.hpp ${CRU_UI_INCLUDE_DIR}/controls/Base.hpp ${CRU_UI_INCLUDE_DIR}/controls/Button.hpp ${CRU_UI_INCLUDE_DIR}/controls/Container.hpp diff --git a/src/ui/ContentControl.cpp b/src/ui/ContentControl.cpp index 8d1a17d2..60d944d6 100644 --- a/src/ui/ContentControl.cpp +++ b/src/ui/ContentControl.cpp @@ -12,16 +12,16 @@ void ContentControl::SetChild(Control* child) { Expects(!dynamic_cast(child)); // Can't add a window as child. if (child == child_) return; - const auto host = GetUiHost(); + const auto host = GetWindowHost(); const auto old_child = child_; child_ = child; if (old_child) { old_child->_SetParent(nullptr); - old_child->_SetDescendantUiHost(nullptr); + old_child->_SetDescendantWindowHost(nullptr); } if (child) { child->_SetParent(this); - child->_SetDescendantUiHost(host); + child->_SetDescendantWindowHost(host); } OnChildChanged(old_child, child); } diff --git a/src/ui/Control.cpp b/src/ui/Control.cpp index cd1367fe..cd7ed0dc 100644 --- a/src/ui/Control.cpp +++ b/src/ui/Control.cpp @@ -3,7 +3,7 @@ #include "cru/platform/native/Cursor.hpp" #include "cru/platform/native/UiApplication.hpp" #include "cru/ui/Base.hpp" -#include "cru/ui/UiHost.hpp" +#include "cru/ui/WindowHost.hpp" #include "RoutedEventDispatch.hpp" #include @@ -32,7 +32,7 @@ void Control::_SetParent(Control* parent) { if (old_parent != new_parent) OnParentChanged(old_parent, new_parent); } -void Control::_SetDescendantUiHost(UiHost* host) { +void Control::_SetDescendantWindowHost(WindowHost* host) { if (host == nullptr && ui_host_ == nullptr) return; // You can only attach or detach window. @@ -64,35 +64,35 @@ void Control::_TraverseDescendants( } bool Control::RequestFocus() { - auto host = GetUiHost(); + auto host = GetWindowHost(); if (host == nullptr) return false; return host->RequestFocusFor(this); } bool Control::HasFocus() { - auto host = GetUiHost(); + auto host = GetWindowHost(); if (host == nullptr) return false; return host->GetFocusControl() == this; } bool Control::CaptureMouse() { - auto host = GetUiHost(); + auto host = GetWindowHost(); if (host == nullptr) return false; return host->CaptureMouseFor(this); } bool Control::ReleaseMouse() { - auto host = GetUiHost(); + auto host = GetWindowHost(); if (host == nullptr) return false; return host->CaptureMouseFor(nullptr); } bool Control::IsMouseCaptured() { - auto host = GetUiHost(); + auto host = GetWindowHost(); if (host == nullptr) return false; return host->GetMouseCaptureControl() == this; @@ -113,7 +113,7 @@ std::shared_ptr Control::GetInheritedCursor() { void Control::SetCursor(std::shared_ptr cursor) { cursor_ = std::move(cursor); - const auto host = GetUiHost(); + const auto host = GetWindowHost(); if (host != nullptr) { host->UpdateCursor(); } @@ -124,7 +124,7 @@ void Control::OnParentChanged(Control* old_parent, Control* new_parent) { CRU_UNUSED(new_parent) } -void Control::OnAttachToHost(UiHost* host) { CRU_UNUSED(host) } +void Control::OnAttachToHost(WindowHost* host) { CRU_UNUSED(host) } -void Control::OnDetachFromHost(UiHost* host) { CRU_UNUSED(host) } +void Control::OnDetachFromHost(WindowHost* host) { CRU_UNUSED(host) } } // namespace cru::ui diff --git a/src/ui/LayoutControl.cpp b/src/ui/LayoutControl.cpp index 4813566b..05fcdc4a 100644 --- a/src/ui/LayoutControl.cpp +++ b/src/ui/LayoutControl.cpp @@ -19,7 +19,7 @@ void LayoutControl::AddChild(Control* control, const Index position) { children_.insert(this->children_.cbegin() + position, control); control->_SetParent(this); - control->_SetDescendantUiHost(GetUiHost()); + control->_SetDescendantWindowHost(GetWindowHost()); OnAddChild(control, position); } @@ -36,7 +36,7 @@ void LayoutControl::RemoveChild(const Index position) { children_.erase(i); child->_SetParent(nullptr); - child->_SetDescendantUiHost(nullptr); + child->_SetDescendantWindowHost(nullptr); OnRemoveChild(child, position); } diff --git a/src/ui/UiHost.cpp b/src/ui/UiHost.cpp deleted file mode 100644 index a881c16d..00000000 --- a/src/ui/UiHost.cpp +++ /dev/null @@ -1,416 +0,0 @@ -#include "cru/ui/UiHost.hpp" - -#include "RoutedEventDispatch.hpp" -#include "cru/common/Logger.hpp" -#include "cru/platform/graph/Painter.hpp" -#include "cru/platform/native/InputMethod.hpp" -#include "cru/platform/native/UiApplication.hpp" -#include "cru/platform/native/Window.hpp" -#include "cru/ui/DebugFlags.hpp" -#include "cru/ui/Window.hpp" -#include "cru/ui/render/MeasureRequirement.hpp" -#include "cru/ui/render/WindowRenderObject.hpp" - -namespace cru::ui { -using platform::native::INativeWindow; -using platform::native::IUiApplication; - -namespace event_names { -#ifdef CRU_DEBUG -// clang-format off -#define CRU_DEFINE_EVENT_NAME(name) constexpr const char16_t* name = CRU_MAKE_UNICODE_LITERAL(name); -// clang-format on -#else -#define CRU_DEFINE_EVENT_NAME(name) constexpr const char16_t* name = u""; -#endif - -CRU_DEFINE_EVENT_NAME(LoseFocus) -CRU_DEFINE_EVENT_NAME(GainFocus) -CRU_DEFINE_EVENT_NAME(MouseEnter) -CRU_DEFINE_EVENT_NAME(MouseLeave) -CRU_DEFINE_EVENT_NAME(MouseMove) -CRU_DEFINE_EVENT_NAME(MouseDown) -CRU_DEFINE_EVENT_NAME(MouseUp) -CRU_DEFINE_EVENT_NAME(KeyDown) -CRU_DEFINE_EVENT_NAME(KeyUp) - -#undef CRU_DEFINE_EVENT_NAME -} // namespace event_names - -namespace { -bool IsAncestor(Control* control, Control* ancestor) { - while (control != nullptr) { - if (control == ancestor) return true; - control = control->GetParent(); - } - return false; -} - -// Ancestor at last. -std::vector GetAncestorList(Control* control) { - std::vector l; - while (control != nullptr) { - l.push_back(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.back() != right_list.back()) return nullptr; - - // find the last same control or the last control (one is ancestor of the - // other) - auto left_iter = left_list.crbegin(); - auto right_iter = right_list.crbegin(); - - while (true) { - if (left_iter == left_list.crend()) { - return left_list.front(); - } - if (right_iter == right_list.crend()) { - return right_list.front(); - } - if (*left_iter != *right_iter) { - return *(--left_iter); - } - ++left_iter; - ++right_iter; - } -} -} // namespace - -namespace { -template -inline void BindNativeEvent( - UiHost* host, INativeWindow* native_window, IEvent* event, - void (UiHost::*handler)(INativeWindow*, typename IEvent::EventArgs), - std::vector& guard_pool) { - guard_pool.push_back(EventRevokerGuard(event->AddHandler( - std::bind(handler, host, native_window, std::placeholders::_1)))); -} -} // namespace - -UiHost::UiHost(Window* window) - : window_control_(window), - mouse_hover_control_(nullptr), - focus_control_(window), - mouse_captured_control_(nullptr) { - const auto ui_application = IUiApplication::GetInstance(); - native_window_resolver_ = ui_application->CreateWindow(nullptr); - - const auto native_window = native_window_resolver_->Resolve(); - - auto input_method_context = - ui_application->GetInputMethodManager()->GetContext(native_window); - input_method_context->DisableIME(); - - window->ui_host_ = this; - - root_render_object_ = std::make_unique(this); - root_render_object_->SetAttachedControl(window); - window->render_object_ = root_render_object_.get(); - - BindNativeEvent(this, native_window, native_window->DestroyEvent(), - &UiHost::OnNativeDestroy, event_revoker_guards_); - BindNativeEvent(this, native_window, native_window->PaintEvent(), - &UiHost::OnNativePaint, event_revoker_guards_); - BindNativeEvent(this, native_window, native_window->ResizeEvent(), - &UiHost::OnNativeResize, event_revoker_guards_); - BindNativeEvent(this, native_window, native_window->FocusEvent(), - &UiHost::OnNativeFocus, event_revoker_guards_); - BindNativeEvent(this, native_window, native_window->MouseEnterLeaveEvent(), - &UiHost::OnNativeMouseEnterLeave, event_revoker_guards_); - BindNativeEvent(this, native_window, native_window->MouseMoveEvent(), - &UiHost::OnNativeMouseMove, event_revoker_guards_); - BindNativeEvent(this, native_window, native_window->MouseDownEvent(), - &UiHost::OnNativeMouseDown, event_revoker_guards_); - BindNativeEvent(this, native_window, native_window->MouseUpEvent(), - &UiHost::OnNativeMouseUp, event_revoker_guards_); - BindNativeEvent(this, native_window, native_window->KeyDownEvent(), - &UiHost::OnNativeKeyDown, event_revoker_guards_); - BindNativeEvent(this, native_window, native_window->KeyUpEvent(), - &UiHost::OnNativeKeyUp, event_revoker_guards_); -} - -UiHost::~UiHost() { - deleting_ = true; - window_control_->TraverseDescendants( - [this](Control* control) { control->OnDetachFromHost(this); }); - if (!native_window_destroyed_) { - const auto native_window = native_window_resolver_->Resolve(); - if (native_window) { - native_window->Close(); - } - } -} - -void UiHost::InvalidatePaint() { - if (const auto native_window = native_window_resolver_->Resolve()) - native_window->RequestRepaint(); -} - -void UiHost::InvalidateLayout() { - if constexpr (debug_flags::layout) - log::TagDebug(log_tag, u"A relayout is requested."); - if (!need_layout_) { - platform::native::IUiApplication::GetInstance()->SetImmediate( - [resolver = this->CreateResolver()] { - if (const auto host = resolver.Resolve()) { - host->Relayout(); - host->need_layout_ = false; - host->InvalidatePaint(); - } - }); - need_layout_ = true; - } -} - -bool UiHost::IsLayoutPreferToFillWindow() const { - return layout_prefer_to_fill_window_; -} - -void UiHost::SetLayoutPreferToFillWindow(bool value) { - if (value == layout_prefer_to_fill_window_) return; - layout_prefer_to_fill_window_ = value; - InvalidateLayout(); -} - -void UiHost::Relayout() { - const auto native_window = native_window_resolver_->Resolve(); - const auto client_size = native_window - ? native_window->GetClientSize() - : Size{100, 100}; // a reasonable assumed size - - root_render_object_->Measure( - render::MeasureRequirement{client_size, - IsLayoutPreferToFillWindow() - ? render::MeasureSize(client_size) - : render::MeasureSize::NotSpecified()}, - render::MeasureSize::NotSpecified()); - root_render_object_->Layout(Point{}); - for (auto& action : after_layout_stable_action_) action(); - after_layout_stable_action_.clear(); - after_layout_event_.Raise(AfterLayoutEventArgs{}); - if constexpr (debug_flags::layout) - log::TagDebug(log_tag, u"A relayout is finished."); -} - -bool UiHost::RequestFocusFor(Control* control) { - Expects(control != nullptr); // The control to request focus can't be null. - // You can set it as the window. - - if (focus_control_ == control) return true; - - const auto old_focus_control = focus_control_; - - focus_control_ = control; - - DispatchEvent(event_names::LoseFocus, old_focus_control, - &Control::LoseFocusEvent, nullptr, false); - - DispatchEvent(event_names::GainFocus, control, &Control::GainFocusEvent, - nullptr, false); - - return true; -} - -Control* UiHost::GetFocusControl() { return focus_control_; } - -bool UiHost::CaptureMouseFor(Control* control) { - const auto native_window = native_window_resolver_->Resolve(); - if (!native_window) return false; - - if (control == mouse_captured_control_) return true; - - if (control == nullptr) { - const auto old_capture_control = mouse_captured_control_; - mouse_captured_control_ = - nullptr; // update this in case this is used in event handlers - if (old_capture_control != mouse_hover_control_) { - DispatchMouseHoverControlChangeEvent( - old_capture_control, mouse_hover_control_, - native_window->GetMousePosition(), true, false); - } - UpdateCursor(); - return true; - } - - if (mouse_captured_control_) return false; - - mouse_captured_control_ = control; - DispatchMouseHoverControlChangeEvent( - mouse_hover_control_, mouse_captured_control_, - native_window->GetMousePosition(), false, true); - UpdateCursor(); - return true; -} - -Control* UiHost::GetMouseCaptureControl() { return mouse_captured_control_; } - -void UiHost::RunAfterLayoutStable(std::function action) { - if (need_layout_) { - after_layout_stable_action_.push_back(std::move(action)); - } else { - action(); - } -} - -void UiHost::OnNativeDestroy(INativeWindow* window, std::nullptr_t) { - CRU_UNUSED(window) - native_window_destroyed_ = true; - if (!deleting_ && !retain_after_destroy_) delete window_control_; -} - -void UiHost::OnNativePaint(INativeWindow* window, std::nullptr_t) { - auto painter = window->BeginPaint(); - painter->Clear(colors::white); - root_render_object_->Draw(painter.get()); - painter->EndDraw(); -} - -void UiHost::OnNativeResize(INativeWindow* window, const Size& size) { - CRU_UNUSED(window) - CRU_UNUSED(size) - - InvalidateLayout(); -} - -void UiHost::OnNativeFocus(INativeWindow* window, - platform::native::FocusChangeType focus) { - CRU_UNUSED(window) - - focus == platform::native::FocusChangeType::Gain - ? DispatchEvent(event_names::GainFocus, focus_control_, - &Control::GainFocusEvent, nullptr, true) - : DispatchEvent(event_names::LoseFocus, focus_control_, - &Control::LoseFocusEvent, nullptr, true); -} - -void UiHost::OnNativeMouseEnterLeave( - INativeWindow* window, platform::native::MouseEnterLeaveType type) { - CRU_UNUSED(window) - - if (type == platform::native::MouseEnterLeaveType::Leave) { - DispatchEvent(event_names::MouseLeave, mouse_hover_control_, - &Control::MouseLeaveEvent, nullptr); - mouse_hover_control_ = nullptr; - } -} - -void UiHost::OnNativeMouseMove(INativeWindow* window, const Point& point) { - CRU_UNUSED(window) - - // Find the first control that hit test succeed. - const auto new_mouse_hover_control = HitTest(point); - const auto old_mouse_hover_control = mouse_hover_control_; - mouse_hover_control_ = new_mouse_hover_control; - - if (mouse_captured_control_) { - const auto n = FindLowestCommonAncestor(new_mouse_hover_control, - mouse_captured_control_); - const auto o = FindLowestCommonAncestor(old_mouse_hover_control, - mouse_captured_control_); - bool a = IsAncestor(o, n); - if (a) { - DispatchEvent(event_names::MouseLeave, o, &Control::MouseLeaveEvent, n); - } else { - DispatchEvent(event_names::MouseEnter, n, &Control::MouseEnterEvent, o, - point); - } - DispatchEvent(event_names::MouseMove, mouse_captured_control_, - &Control::MouseMoveEvent, nullptr, point); - UpdateCursor(); - return; - } - - DispatchMouseHoverControlChangeEvent( - old_mouse_hover_control, new_mouse_hover_control, point, false, false); - DispatchEvent(event_names::MouseMove, new_mouse_hover_control, - &Control::MouseMoveEvent, nullptr, point); - UpdateCursor(); -} - -void UiHost::OnNativeMouseDown( - INativeWindow* window, - const platform::native::NativeMouseButtonEventArgs& args) { - CRU_UNUSED(window) - - Control* control = - mouse_captured_control_ ? mouse_captured_control_ : HitTest(args.point); - DispatchEvent(event_names::MouseDown, control, &Control::MouseDownEvent, - nullptr, args.point, args.button, args.modifier); -} - -void UiHost::OnNativeMouseUp( - INativeWindow* window, - const platform::native::NativeMouseButtonEventArgs& args) { - CRU_UNUSED(window) - - Control* control = - mouse_captured_control_ ? mouse_captured_control_ : HitTest(args.point); - DispatchEvent(event_names::MouseUp, control, &Control::MouseUpEvent, nullptr, - args.point, args.button, args.modifier); -} - -void UiHost::OnNativeKeyDown(INativeWindow* window, - const platform::native::NativeKeyEventArgs& args) { - CRU_UNUSED(window) - - DispatchEvent(event_names::KeyDown, focus_control_, &Control::KeyDownEvent, - nullptr, args.key, args.modifier); -} - -void UiHost::OnNativeKeyUp(INativeWindow* window, - const platform::native::NativeKeyEventArgs& args) { - CRU_UNUSED(window) - - DispatchEvent(event_names::KeyUp, focus_control_, &Control::KeyUpEvent, - nullptr, args.key, args.modifier); -} - -void UiHost::DispatchMouseHoverControlChangeEvent(Control* old_control, - Control* new_control, - const Point& point, - bool no_leave, - bool no_enter) { - if (new_control != old_control) // if the mouse-hover-on control changed - { - const auto lowest_common_ancestor = - FindLowestCommonAncestor(old_control, new_control); - if (!no_leave && old_control != nullptr) - DispatchEvent(event_names::MouseLeave, old_control, - &Control::MouseLeaveEvent, - lowest_common_ancestor); // dispatch mouse leave event. - if (!no_enter && new_control != nullptr) { - DispatchEvent(event_names::MouseEnter, new_control, - &Control::MouseEnterEvent, lowest_common_ancestor, - point); // dispatch mouse enter event. - } - } -} - -void UiHost::UpdateCursor() { - if (const auto native_window = native_window_resolver_->Resolve()) { - const auto capture = GetMouseCaptureControl(); - native_window->SetCursor( - (capture ? capture : GetMouseHoverControl())->GetInheritedCursor()); - } -} - -Control* UiHost::HitTest(const Point& point) { - const auto render_object = root_render_object_->HitTest(point); - if (render_object) { - const auto control = render_object->GetAttachedControl(); - Ensures(control); - return control; - } - return window_control_; -} -} // namespace cru::ui diff --git a/src/ui/Window.cpp b/src/ui/Window.cpp index dca95ebb..a8cb315b 100644 --- a/src/ui/Window.cpp +++ b/src/ui/Window.cpp @@ -1,7 +1,7 @@ #include "cru/ui/Window.hpp" #include "cru/ui/render/WindowRenderObject.hpp" -#include "cru/ui/UiHost.hpp" +#include "cru/ui/WindowHost.hpp" namespace cru::ui { Window* Window::CreateOverlapped() { @@ -9,7 +9,7 @@ Window* Window::CreateOverlapped() { } Window::Window(tag_overlapped_constructor) { - managed_ui_host_ = std::make_unique(this); + managed_ui_host_ = std::make_unique(this); } Window::~Window() { diff --git a/src/ui/WindowHost.cpp b/src/ui/WindowHost.cpp new file mode 100644 index 00000000..d3dec422 --- /dev/null +++ b/src/ui/WindowHost.cpp @@ -0,0 +1,418 @@ +#include "cru/ui/WindowHost.hpp" + +#include "RoutedEventDispatch.hpp" +#include "cru/common/Logger.hpp" +#include "cru/platform/graph/Painter.hpp" +#include "cru/platform/native/InputMethod.hpp" +#include "cru/platform/native/UiApplication.hpp" +#include "cru/platform/native/Window.hpp" +#include "cru/ui/DebugFlags.hpp" +#include "cru/ui/Window.hpp" +#include "cru/ui/render/MeasureRequirement.hpp" +#include "cru/ui/render/WindowRenderObject.hpp" + +namespace cru::ui { +using platform::native::INativeWindow; +using platform::native::IUiApplication; + +namespace event_names { +#ifdef CRU_DEBUG +// clang-format off +#define CRU_DEFINE_EVENT_NAME(name) constexpr const char16_t* name = CRU_MAKE_UNICODE_LITERAL(name); +// clang-format on +#else +#define CRU_DEFINE_EVENT_NAME(name) constexpr const char16_t* name = u""; +#endif + +CRU_DEFINE_EVENT_NAME(LoseFocus) +CRU_DEFINE_EVENT_NAME(GainFocus) +CRU_DEFINE_EVENT_NAME(MouseEnter) +CRU_DEFINE_EVENT_NAME(MouseLeave) +CRU_DEFINE_EVENT_NAME(MouseMove) +CRU_DEFINE_EVENT_NAME(MouseDown) +CRU_DEFINE_EVENT_NAME(MouseUp) +CRU_DEFINE_EVENT_NAME(KeyDown) +CRU_DEFINE_EVENT_NAME(KeyUp) + +#undef CRU_DEFINE_EVENT_NAME +} // namespace event_names + +namespace { +bool IsAncestor(Control* control, Control* ancestor) { + while (control != nullptr) { + if (control == ancestor) return true; + control = control->GetParent(); + } + return false; +} + +// Ancestor at last. +std::vector GetAncestorList(Control* control) { + std::vector l; + while (control != nullptr) { + l.push_back(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.back() != right_list.back()) return nullptr; + + // find the last same control or the last control (one is ancestor of the + // other) + auto left_iter = left_list.crbegin(); + auto right_iter = right_list.crbegin(); + + while (true) { + if (left_iter == left_list.crend()) { + return left_list.front(); + } + if (right_iter == right_list.crend()) { + return right_list.front(); + } + if (*left_iter != *right_iter) { + return *(--left_iter); + } + ++left_iter; + ++right_iter; + } +} +} // namespace + +namespace { +template +inline void BindNativeEvent( + WindowHost* host, INativeWindow* native_window, IEvent* event, + void (WindowHost::*handler)(INativeWindow*, typename IEvent::EventArgs), + std::vector& guard_pool) { + guard_pool.push_back(EventRevokerGuard(event->AddHandler( + std::bind(handler, host, native_window, std::placeholders::_1)))); +} +} // namespace + +WindowHost::WindowHost(Window* window) + : window_control_(window), + mouse_hover_control_(nullptr), + focus_control_(window), + mouse_captured_control_(nullptr) { + const auto ui_application = IUiApplication::GetInstance(); + native_window_resolver_ = ui_application->CreateWindow(nullptr); + + const auto native_window = native_window_resolver_->Resolve(); + + auto input_method_context = + ui_application->GetInputMethodManager()->GetContext(native_window); + input_method_context->DisableIME(); + + window->ui_host_ = this; + + root_render_object_ = std::make_unique(this); + root_render_object_->SetAttachedControl(window); + window->render_object_ = root_render_object_.get(); + + BindNativeEvent(this, native_window, native_window->DestroyEvent(), + &WindowHost::OnNativeDestroy, event_revoker_guards_); + BindNativeEvent(this, native_window, native_window->PaintEvent(), + &WindowHost::OnNativePaint, event_revoker_guards_); + BindNativeEvent(this, native_window, native_window->ResizeEvent(), + &WindowHost::OnNativeResize, event_revoker_guards_); + BindNativeEvent(this, native_window, native_window->FocusEvent(), + &WindowHost::OnNativeFocus, event_revoker_guards_); + BindNativeEvent(this, native_window, native_window->MouseEnterLeaveEvent(), + &WindowHost::OnNativeMouseEnterLeave, event_revoker_guards_); + BindNativeEvent(this, native_window, native_window->MouseMoveEvent(), + &WindowHost::OnNativeMouseMove, event_revoker_guards_); + BindNativeEvent(this, native_window, native_window->MouseDownEvent(), + &WindowHost::OnNativeMouseDown, event_revoker_guards_); + BindNativeEvent(this, native_window, native_window->MouseUpEvent(), + &WindowHost::OnNativeMouseUp, event_revoker_guards_); + BindNativeEvent(this, native_window, native_window->KeyDownEvent(), + &WindowHost::OnNativeKeyDown, event_revoker_guards_); + BindNativeEvent(this, native_window, native_window->KeyUpEvent(), + &WindowHost::OnNativeKeyUp, event_revoker_guards_); +} + +WindowHost::~WindowHost() { + deleting_ = true; + window_control_->TraverseDescendants( + [this](Control* control) { control->OnDetachFromHost(this); }); + if (!native_window_destroyed_) { + const auto native_window = native_window_resolver_->Resolve(); + if (native_window) { + native_window->Close(); + } + } +} + +void WindowHost::InvalidatePaint() { + if (const auto native_window = native_window_resolver_->Resolve()) + native_window->RequestRepaint(); +} + +void WindowHost::InvalidateLayout() { + if constexpr (debug_flags::layout) + log::TagDebug(log_tag, u"A relayout is requested."); + if (!need_layout_) { + platform::native::IUiApplication::GetInstance()->SetImmediate( + [resolver = this->CreateResolver()] { + if (const auto host = resolver.Resolve()) { + host->Relayout(); + host->need_layout_ = false; + host->InvalidatePaint(); + } + }); + need_layout_ = true; + } +} + +bool WindowHost::IsLayoutPreferToFillWindow() const { + return layout_prefer_to_fill_window_; +} + +void WindowHost::SetLayoutPreferToFillWindow(bool value) { + if (value == layout_prefer_to_fill_window_) return; + layout_prefer_to_fill_window_ = value; + InvalidateLayout(); +} + +void WindowHost::Relayout() { + const auto native_window = native_window_resolver_->Resolve(); + const auto client_size = native_window + ? native_window->GetClientSize() + : Size{100, 100}; // a reasonable assumed size + + root_render_object_->Measure( + render::MeasureRequirement{client_size, + IsLayoutPreferToFillWindow() + ? render::MeasureSize(client_size) + : render::MeasureSize::NotSpecified()}, + render::MeasureSize::NotSpecified()); + root_render_object_->Layout(Point{}); + for (auto& action : after_layout_stable_action_) action(); + after_layout_stable_action_.clear(); + after_layout_event_.Raise(AfterLayoutEventArgs{}); + if constexpr (debug_flags::layout) + log::TagDebug(log_tag, u"A relayout is finished."); +} + +bool WindowHost::RequestFocusFor(Control* control) { + Expects(control != nullptr); // The control to request focus can't be null. + // You can set it as the window. + + if (focus_control_ == control) return true; + + const auto old_focus_control = focus_control_; + + focus_control_ = control; + + DispatchEvent(event_names::LoseFocus, old_focus_control, + &Control::LoseFocusEvent, nullptr, false); + + DispatchEvent(event_names::GainFocus, control, &Control::GainFocusEvent, + nullptr, false); + + return true; +} + +Control* WindowHost::GetFocusControl() { return focus_control_; } + +bool WindowHost::CaptureMouseFor(Control* control) { + const auto native_window = native_window_resolver_->Resolve(); + if (!native_window) return false; + + if (control == mouse_captured_control_) return true; + + if (control == nullptr) { + const auto old_capture_control = mouse_captured_control_; + mouse_captured_control_ = + nullptr; // update this in case this is used in event handlers + if (old_capture_control != mouse_hover_control_) { + DispatchMouseHoverControlChangeEvent( + old_capture_control, mouse_hover_control_, + native_window->GetMousePosition(), true, false); + } + UpdateCursor(); + return true; + } + + if (mouse_captured_control_) return false; + + mouse_captured_control_ = control; + DispatchMouseHoverControlChangeEvent( + mouse_hover_control_, mouse_captured_control_, + native_window->GetMousePosition(), false, true); + UpdateCursor(); + return true; +} + +Control* WindowHost::GetMouseCaptureControl() { + return mouse_captured_control_; +} + +void WindowHost::RunAfterLayoutStable(std::function action) { + if (need_layout_) { + after_layout_stable_action_.push_back(std::move(action)); + } else { + action(); + } +} + +void WindowHost::OnNativeDestroy(INativeWindow* window, std::nullptr_t) { + CRU_UNUSED(window) + native_window_destroyed_ = true; + if (!deleting_ && !retain_after_destroy_) delete window_control_; +} + +void WindowHost::OnNativePaint(INativeWindow* window, std::nullptr_t) { + auto painter = window->BeginPaint(); + painter->Clear(colors::white); + root_render_object_->Draw(painter.get()); + painter->EndDraw(); +} + +void WindowHost::OnNativeResize(INativeWindow* window, const Size& size) { + CRU_UNUSED(window) + CRU_UNUSED(size) + + InvalidateLayout(); +} + +void WindowHost::OnNativeFocus(INativeWindow* window, + platform::native::FocusChangeType focus) { + CRU_UNUSED(window) + + focus == platform::native::FocusChangeType::Gain + ? DispatchEvent(event_names::GainFocus, focus_control_, + &Control::GainFocusEvent, nullptr, true) + : DispatchEvent(event_names::LoseFocus, focus_control_, + &Control::LoseFocusEvent, nullptr, true); +} + +void WindowHost::OnNativeMouseEnterLeave( + INativeWindow* window, platform::native::MouseEnterLeaveType type) { + CRU_UNUSED(window) + + if (type == platform::native::MouseEnterLeaveType::Leave) { + DispatchEvent(event_names::MouseLeave, mouse_hover_control_, + &Control::MouseLeaveEvent, nullptr); + mouse_hover_control_ = nullptr; + } +} + +void WindowHost::OnNativeMouseMove(INativeWindow* window, const Point& point) { + CRU_UNUSED(window) + + // Find the first control that hit test succeed. + const auto new_mouse_hover_control = HitTest(point); + const auto old_mouse_hover_control = mouse_hover_control_; + mouse_hover_control_ = new_mouse_hover_control; + + if (mouse_captured_control_) { + const auto n = FindLowestCommonAncestor(new_mouse_hover_control, + mouse_captured_control_); + const auto o = FindLowestCommonAncestor(old_mouse_hover_control, + mouse_captured_control_); + bool a = IsAncestor(o, n); + if (a) { + DispatchEvent(event_names::MouseLeave, o, &Control::MouseLeaveEvent, n); + } else { + DispatchEvent(event_names::MouseEnter, n, &Control::MouseEnterEvent, o, + point); + } + DispatchEvent(event_names::MouseMove, mouse_captured_control_, + &Control::MouseMoveEvent, nullptr, point); + UpdateCursor(); + return; + } + + DispatchMouseHoverControlChangeEvent( + old_mouse_hover_control, new_mouse_hover_control, point, false, false); + DispatchEvent(event_names::MouseMove, new_mouse_hover_control, + &Control::MouseMoveEvent, nullptr, point); + UpdateCursor(); +} + +void WindowHost::OnNativeMouseDown( + INativeWindow* window, + const platform::native::NativeMouseButtonEventArgs& args) { + CRU_UNUSED(window) + + Control* control = + mouse_captured_control_ ? mouse_captured_control_ : HitTest(args.point); + DispatchEvent(event_names::MouseDown, control, &Control::MouseDownEvent, + nullptr, args.point, args.button, args.modifier); +} + +void WindowHost::OnNativeMouseUp( + INativeWindow* window, + const platform::native::NativeMouseButtonEventArgs& args) { + CRU_UNUSED(window) + + Control* control = + mouse_captured_control_ ? mouse_captured_control_ : HitTest(args.point); + DispatchEvent(event_names::MouseUp, control, &Control::MouseUpEvent, nullptr, + args.point, args.button, args.modifier); +} + +void WindowHost::OnNativeKeyDown( + INativeWindow* window, const platform::native::NativeKeyEventArgs& args) { + CRU_UNUSED(window) + + DispatchEvent(event_names::KeyDown, focus_control_, &Control::KeyDownEvent, + nullptr, args.key, args.modifier); +} + +void WindowHost::OnNativeKeyUp( + INativeWindow* window, const platform::native::NativeKeyEventArgs& args) { + CRU_UNUSED(window) + + DispatchEvent(event_names::KeyUp, focus_control_, &Control::KeyUpEvent, + nullptr, args.key, args.modifier); +} + +void WindowHost::DispatchMouseHoverControlChangeEvent(Control* old_control, + Control* new_control, + const Point& point, + bool no_leave, + bool no_enter) { + if (new_control != old_control) // if the mouse-hover-on control changed + { + const auto lowest_common_ancestor = + FindLowestCommonAncestor(old_control, new_control); + if (!no_leave && old_control != nullptr) + DispatchEvent(event_names::MouseLeave, old_control, + &Control::MouseLeaveEvent, + lowest_common_ancestor); // dispatch mouse leave event. + if (!no_enter && new_control != nullptr) { + DispatchEvent(event_names::MouseEnter, new_control, + &Control::MouseEnterEvent, lowest_common_ancestor, + point); // dispatch mouse enter event. + } + } +} + +void WindowHost::UpdateCursor() { + if (const auto native_window = native_window_resolver_->Resolve()) { + const auto capture = GetMouseCaptureControl(); + native_window->SetCursor( + (capture ? capture : GetMouseHoverControl())->GetInheritedCursor()); + } +} + +Control* WindowHost::HitTest(const Point& point) { + const auto render_object = root_render_object_->HitTest(point); + if (render_object) { + const auto control = render_object->GetAttachedControl(); + Ensures(control); + return control; + } + return window_control_; +} +} // namespace cru::ui diff --git a/src/ui/controls/TextControlService.hpp b/src/ui/controls/TextControlService.hpp index 8419f35c..8c1bd32f 100644 --- a/src/ui/controls/TextControlService.hpp +++ b/src/ui/controls/TextControlService.hpp @@ -12,7 +12,7 @@ #include "cru/ui/DebugFlags.hpp" #include "cru/ui/ShortcutHub.hpp" #include "cru/ui/UiEvent.hpp" -#include "cru/ui/UiHost.hpp" +#include "cru/ui/WindowHost.hpp" #include "cru/ui/render/CanvasRenderObject.hpp" #include "cru/ui/render/ScrollRenderObject.hpp" #include "cru/ui/render/TextRenderObject.hpp" @@ -208,7 +208,7 @@ class TextControlService : public Object { } void ScrollToCaret() { - this->control_->GetUiHost()->RunAfterLayoutStable([this]() { + this->control_->GetWindowHost()->RunAfterLayoutStable([this]() { const auto caret_rect = this->GetTextRenderObject()->GetCaretRect(); this->GetScrollRenderObject()->ScrollToContain(caret_rect, Thickness{5.f}); @@ -408,7 +408,7 @@ class TextControlService : public Object { void GainFocusHandler(event::FocusChangeEventArgs& args) { CRU_UNUSED(args); if (editable_) { - UiHost* ui_host = this->control_->GetUiHost(); + WindowHost* ui_host = this->control_->GetWindowHost(); auto window = ui_host->GetNativeWindowResolver()->Resolve(); if (window == nullptr) return; input_method_context_ = diff --git a/src/ui/render/RenderObject.cpp b/src/ui/render/RenderObject.cpp index c85f8080..5266daaf 100644 --- a/src/ui/render/RenderObject.cpp +++ b/src/ui/render/RenderObject.cpp @@ -3,7 +3,7 @@ #include "cru/common/Logger.hpp" #include "cru/platform/graph/util/Painter.hpp" #include "cru/ui/DebugFlags.hpp" -#include "cru/ui/UiHost.hpp" +#include "cru/ui/WindowHost.hpp" #include #include @@ -24,7 +24,7 @@ void RenderObject::AddChild(RenderObject* render_object, const Index position) { children_.insert(children_.cbegin() + position, render_object); render_object->SetParent(this); - render_object->SetRenderHostRecursive(GetUiHost()); + render_object->SetRenderHostRecursive(GetWindowHost()); OnAddChild(render_object, position); } @@ -304,7 +304,7 @@ void RenderObject::NotifyAfterLayoutRecursive(RenderObject* render_object) { } } -void RenderObject::SetRenderHostRecursive(UiHost* host) { +void RenderObject::SetRenderHostRecursive(WindowHost* host) { ui_host_ = host; for (const auto child : GetChildren()) { child->SetRenderHostRecursive(host); diff --git a/src/ui/render/WindowRenderObject.cpp b/src/ui/render/WindowRenderObject.cpp index a136c1e9..23cca12e 100644 --- a/src/ui/render/WindowRenderObject.cpp +++ b/src/ui/render/WindowRenderObject.cpp @@ -2,10 +2,10 @@ #include "../Helper.hpp" #include "cru/platform/graph/util/Painter.hpp" -#include "cru/ui/UiHost.hpp" +#include "cru/ui/WindowHost.hpp" namespace cru::ui::render { -WindowRenderObject::WindowRenderObject(UiHost* host) { +WindowRenderObject::WindowRenderObject(WindowHost* host) { SetChildMode(ChildMode::Single); ui_host_ = host; after_layout_event_guard_.Reset(host->AfterLayoutEvent()->AddHandler( -- cgit v1.2.3 From 52594324b302f6e9da10ac01fe803196371bb2d9 Mon Sep 17 00:00:00 2001 From: crupest Date: Thu, 29 Oct 2020 00:01:26 +0800 Subject: ... --- demos/input_method/main.cpp | 7 +- demos/main/main.cpp | 6 +- include/cru/ui/ContentControl.hpp | 13 ++-- include/cru/ui/Control.hpp | 29 ++++---- include/cru/ui/LayoutControl.hpp | 18 +---- include/cru/ui/NoChildControl.hpp | 10 +-- include/cru/ui/Window.hpp | 18 ++--- include/cru/ui/WindowHost.hpp | 72 +++++++----------- include/cru/ui/render/Base.hpp | 1 - include/cru/ui/render/RenderObject.hpp | 20 +++-- include/cru/ui/render/WindowRenderObject.hpp | 34 --------- src/ui/CMakeLists.txt | 2 - src/ui/ContentControl.cpp | 24 +++--- src/ui/Control.cpp | 106 +++++++++++++++++---------- src/ui/LayoutControl.cpp | 47 ------------ src/ui/NoChildControl.cpp | 4 +- src/ui/Window.cpp | 31 ++++---- src/ui/WindowHost.cpp | 98 ++++++++++--------------- src/ui/controls/TextControlService.hpp | 77 +++++++++++-------- src/ui/render/RenderObject.cpp | 25 +++---- src/ui/render/WindowRenderObject.cpp | 44 ----------- src/win/native/UiApplication.cpp | 5 -- src/win/native/Window.cpp | 1 + 23 files changed, 271 insertions(+), 421 deletions(-) delete mode 100644 include/cru/ui/render/WindowRenderObject.hpp delete mode 100644 src/ui/render/WindowRenderObject.cpp (limited to 'demos/main/main.cpp') diff --git a/demos/input_method/main.cpp b/demos/input_method/main.cpp index bff0e1d3..06098253 100644 --- a/demos/input_method/main.cpp +++ b/demos/input_method/main.cpp @@ -14,12 +14,9 @@ int main() { auto graph_factory = application->GetGraphFactory(); - auto window_resolver = application->CreateWindow(nullptr); + auto window = application->CreateWindow(nullptr); - auto window = window_resolver->Resolve(); - - auto input_method_context = - application->GetInputMethodManager()->GetContext(window); + auto input_method_context = window->GetInputMethodContext(); auto brush = graph_factory->CreateSolidColorBrush(); brush->SetColor(colors::black); diff --git a/demos/main/main.cpp b/demos/main/main.cpp index f7635231..e973682e 100644 --- a/demos/main/main.cpp +++ b/demos/main/main.cpp @@ -2,8 +2,8 @@ #include "cru/platform/native/UiApplication.hpp" #include "cru/platform/native/Window.hpp" #include "cru/ui/Base.hpp" -#include "cru/ui/WindowHost.hpp" #include "cru/ui/Window.hpp" +#include "cru/ui/WindowHost.hpp" #include "cru/ui/controls/Button.hpp" #include "cru/ui/controls/FlexLayout.hpp" #include "cru/ui/controls/TextBlock.hpp" @@ -30,7 +30,7 @@ int main() { flex_layout->SetContentMainAlign(cru::ui::FlexCrossAlignment::Center); flex_layout->SetItemCrossAlign(cru::ui::FlexCrossAlignment::Center); - window->SetChild(flex_layout); + window->AddChild(flex_layout, 0); const auto text_block = TextBlock::Create(); text_block->SetText(u"Hello World from CruUI!"); @@ -45,7 +45,7 @@ int main() { const auto text_box = TextBox::Create(); flex_layout->AddChild(text_box, 2); - window->GetWindowHost()->GetNativeWindowResolver()->Resolve()->SetVisible(true); + window->GetWindowHost()->GetNativeWindow()->SetVisible(true); return application->Run(); } diff --git a/include/cru/ui/ContentControl.hpp b/include/cru/ui/ContentControl.hpp index 19f13a1d..ba5b6b2f 100644 --- a/include/cru/ui/ContentControl.hpp +++ b/include/cru/ui/ContentControl.hpp @@ -4,26 +4,23 @@ namespace cru::ui { class ContentControl : public Control { protected: - ContentControl(); + ContentControl() = default; public: ContentControl(const ContentControl& other) = delete; ContentControl(ContentControl&& other) = delete; ContentControl& operator=(const ContentControl& other) = delete; ContentControl& operator=(ContentControl&& other) = delete; - ~ContentControl() override; + ~ContentControl() override = default; - const std::vector& GetChildren() const override final { - return child_vector_; - } - Control* GetChild() const { return child_; } + Control* GetChild() const; void SetChild(Control* child); protected: virtual void OnChildChanged(Control* old_child, Control* new_child); private: - std::vector child_vector_; - Control*& child_; + using Control::AddChild; + using Control::RemoveChild; }; } // namespace cru::ui diff --git a/include/cru/ui/Control.hpp b/include/cru/ui/Control.hpp index 692dcc9b..0021ad62 100644 --- a/include/cru/ui/Control.hpp +++ b/include/cru/ui/Control.hpp @@ -1,9 +1,9 @@ #pragma once #include "Base.hpp" +#include "UiEvent.hpp" #include "cru/common/Event.hpp" #include "render/Base.hpp" -#include "UiEvent.hpp" #include @@ -19,39 +19,31 @@ class Control : public Object { Control(Control&& other) = delete; Control& operator=(const Control& other) = delete; Control& operator=(Control&& other) = delete; - ~Control() override = default; + ~Control() override; public: virtual std::u16string_view GetControlType() const = 0; //*************** region: tree *************** public: - // Get the ui host if attached, otherwise, return nullptr. - WindowHost* GetWindowHost() const { return ui_host_; } + WindowHost* GetWindowHost() const; Control* GetParent() const { return parent_; } - virtual const std::vector& GetChildren() const = 0; + const std::vector& GetChildren() const { return children_; } // Traverse the tree rooted the control including itself. void TraverseDescendants(const std::function& predicate); - void _SetParent(Control* parent); - void _SetDescendantWindowHost(WindowHost* host); - - private: - static void _TraverseDescendants( - Control* control, const std::function& predicate); - public: virtual render::RenderObject* GetRenderObject() const = 0; //*************** region: focus *************** public: - bool RequestFocus(); - bool HasFocus(); + void SetFocus(); + //*************** region: mouse *************** public: bool IsMouseOver() const { return is_mouse_over_; } @@ -134,15 +126,22 @@ class Control : public Object { //*************** region: tree *************** protected: + void AddChild(Control* control, Index position); + void RemoveChild(Index position); + virtual void OnAddChild(Control* child, Index position); + virtual void OnRemoveChild(Control* child, Index position); virtual void OnParentChanged(Control* old_parent, Control* new_parent); virtual void OnAttachToHost(WindowHost* host); virtual void OnDetachFromHost(WindowHost* host); + protected: virtual void OnMouseHoverChange(bool newHover) { CRU_UNUSED(newHover) } private: - WindowHost* ui_host_ = nullptr; Control* parent_ = nullptr; + std::vector children_; + + WindowHost* window_host_ = nullptr; private: bool is_mouse_over_ = false; diff --git a/include/cru/ui/LayoutControl.hpp b/include/cru/ui/LayoutControl.hpp index 7997b37e..69d5cd0b 100644 --- a/include/cru/ui/LayoutControl.hpp +++ b/include/cru/ui/LayoutControl.hpp @@ -11,21 +11,9 @@ class LayoutControl : public Control { LayoutControl(LayoutControl&& other) = delete; LayoutControl& operator=(const LayoutControl& other) = delete; LayoutControl& operator=(LayoutControl&& other) = delete; - ~LayoutControl() override; + ~LayoutControl() override = default; - const std::vector& GetChildren() const override final { - return children_; - } - - void AddChild(Control* control, Index position); - - void RemoveChild(Index position); - - protected: - virtual void OnAddChild(Control* child, Index position); - virtual void OnRemoveChild(Control* child, Index position); - - private: - std::vector children_; + using Control::AddChild; + using Control::RemoveChild; }; } // namespace cru::ui diff --git a/include/cru/ui/NoChildControl.hpp b/include/cru/ui/NoChildControl.hpp index 1a31ae7e..0d8a8e34 100644 --- a/include/cru/ui/NoChildControl.hpp +++ b/include/cru/ui/NoChildControl.hpp @@ -3,9 +3,6 @@ namespace cru::ui { class NoChildControl : public Control { - private: - static const std::vector empty_control_vector; - protected: NoChildControl() = default; @@ -16,9 +13,8 @@ class NoChildControl : public Control { NoChildControl& operator=(NoChildControl&& other) = delete; ~NoChildControl() override = default; - protected: - const std::vector& GetChildren() const override final { - return empty_control_vector; - } + private: + using Control::AddChild; + using Control::RemoveChild; }; } // namespace cru::ui diff --git a/include/cru/ui/Window.hpp b/include/cru/ui/Window.hpp index 5ea24855..0739e3dc 100644 --- a/include/cru/ui/Window.hpp +++ b/include/cru/ui/Window.hpp @@ -1,10 +1,8 @@ #pragma once -#include "ContentControl.hpp" +#include "LayoutControl.hpp" namespace cru::ui { -class Window final : public ContentControl { - friend WindowHost; - +class Window final : public LayoutControl { public: static constexpr std::u16string_view control_type = u"Window"; @@ -12,9 +10,7 @@ class Window final : public ContentControl { static Window* CreateOverlapped(); private: - struct tag_overlapped_constructor {}; - - explicit Window(tag_overlapped_constructor); + Window(); public: Window(const Window& other) = delete; @@ -29,12 +25,12 @@ class Window final : public ContentControl { render::RenderObject* GetRenderObject() const override; protected: - void OnChildChanged(Control* old_child, Control* new_child) override; + void OnAddChild(Control* child, Index position) override; + void OnRemoveChild(Control* child, Index position) override; private: - std::unique_ptr managed_ui_host_; + std::unique_ptr window_host_; - // WindowHost is responsible to take care of lifetime of this. - render::WindowRenderObject* render_object_; + std::unique_ptr render_object_; }; } // namespace cru::ui diff --git a/include/cru/ui/WindowHost.hpp b/include/cru/ui/WindowHost.hpp index 83ef2f64..8efb505d 100644 --- a/include/cru/ui/WindowHost.hpp +++ b/include/cru/ui/WindowHost.hpp @@ -1,20 +1,22 @@ #pragma once -#include #include "Base.hpp" #include "cru/common/Event.hpp" -#include "cru/common/SelfResolvable.hpp" +#include "cru/platform/native/UiApplication.hpp" +#include "cru/platform/native/Window.hpp" #include "render/Base.hpp" +#include + namespace cru::ui { struct AfterLayoutEventArgs {}; -class WindowHost : public Object, public SelfResolvable { + +// The bridge between control tree and native window. +class WindowHost : public Object { CRU_DEFINE_CLASS_LOG_TAG(u"cru::ui::WindowHost") public: - // This will create root window render object and attach it to window. - // It will also create and manage a native window. - WindowHost(Window* window); + WindowHost(Control* root_control); CRU_DELETE_COPY(WindowHost) CRU_DELETE_MOVE(WindowHost) @@ -22,6 +24,8 @@ class WindowHost : public Object, public SelfResolvable { ~WindowHost() override; public: + platform::native::INativeWindow* GetNativeWindow() { return native_window_; } + // Mark the layout as invalid, and arrange a re-layout later. // This method could be called more than one times in a message cycle. But // layout only takes place once. @@ -36,13 +40,18 @@ class WindowHost : public Object, public SelfResolvable { return &after_layout_event_; } + void Relayout(); + void Relayout(const Size& available_size); + + // Is layout is invalid, wait for relayout and then run the action. Otherwist + // run it right now. + void RunAfterLayoutStable(std::function action); + // If true, preferred size of root render object is set to window size when // measure. Default is true. bool IsLayoutPreferToFillWindow() const; void SetLayoutPreferToFillWindow(bool value); - void Relayout(); - // Get current control that mouse hovers on. This ignores the mouse-capture // control. Even when mouse is captured by another control, this function // return the control under cursor. You can use `GetMouseCaptureControl` to @@ -51,12 +60,10 @@ class WindowHost : public Object, public SelfResolvable { //*************** region: focus *************** - // Request focus for specified control. - bool RequestFocusFor(Control* control); - - // Get the control that has focus. Control* GetFocusControl(); + void SetFocusControl(Control* control); + //*************** region: focus *************** // Pass nullptr to release capture. If mouse is already capture by a control, @@ -78,19 +85,6 @@ class WindowHost : public Object, public SelfResolvable { void UpdateCursor(); - std::shared_ptr - GetNativeWindowResolver() { - return native_window_resolver_; - } - - bool IsRetainAfterDestroy() { return retain_after_destroy_; } - - void SetRetainAfterDestroy(bool destroy) { retain_after_destroy_ = destroy; } - - // Is layout is invalid, wait for relayout and then run the action. Otherwist - // run it right now. - void RunAfterLayoutStable(std::function action); - private: //*************** region: native messages *************** void OnNativeDestroy(platform::native::INativeWindow* window, std::nullptr_t); @@ -126,33 +120,21 @@ class WindowHost : public Object, public SelfResolvable { bool no_enter); private: - bool need_layout_ = false; + Control* root_control_; + render::RenderObject* root_render_object_; + + platform::native::INativeWindow* native_window_; + bool need_layout_ = false; + platform::native::TimerAutoCanceler relayout_timer_canceler_; Event after_layout_event_; std::vector > after_layout_stable_action_; - std::shared_ptr - native_window_resolver_; - - // See remarks of WindowHost. - bool retain_after_destroy_ = false; - // See remarks of WindowHost. - bool deleting_ = false; - - // We need this because calling Resolve on resolver in handler of destroy - // event is bad and will always get the dying window. But we need to label the - // window as destroyed so the destructor will not destroy native window - // repeatedly. See remarks of WindowHost. - bool native_window_destroyed_ = false; - std::vector event_revoker_guards_; - Window* window_control_; - std::unique_ptr root_render_object_; - - Control* mouse_hover_control_; + Control* mouse_hover_control_ = nullptr; - Control* focus_control_; // "focus_control_" can't be nullptr + Control* focus_control_; Control* mouse_captured_control_; diff --git a/include/cru/ui/render/Base.hpp b/include/cru/ui/render/Base.hpp index 801d58bd..ac67349e 100644 --- a/include/cru/ui/render/Base.hpp +++ b/include/cru/ui/render/Base.hpp @@ -9,5 +9,4 @@ class FlexLayoutRenderObject; class ScrollRenderObject; class StackLayoutRenderObject; class TextRenderObject; -class WindowRenderObject; } // namespace cru::ui::render diff --git a/include/cru/ui/render/RenderObject.hpp b/include/cru/ui/render/RenderObject.hpp index f052221e..4e5c9060 100644 --- a/include/cru/ui/render/RenderObject.hpp +++ b/include/cru/ui/render/RenderObject.hpp @@ -3,12 +3,13 @@ #include "MeasureRequirement.hpp" #include "cru/common/Event.hpp" +#include "cru/ui/Base.hpp" +#include #include #include namespace cru::ui::render { - // Render object will not destroy its children when destroyed. Control must // manage lifecycle of its render objects. Since control will destroy its // children when destroyed, render objects will be destroyed along with it. @@ -38,7 +39,7 @@ namespace cru::ui::render { // Size OnMeasureContent(const MeasureRequirement& requirement) override; // void OnLayoutContent(const Rect& content_rect) override; class RenderObject : public Object { - friend WindowRenderObject; + friend WindowHost; CRU_DEFINE_CLASS_LOG_TAG(u"cru::ui::render::RenderObject") @@ -64,7 +65,7 @@ class RenderObject : public Object { Control* GetAttachedControl() const { return control_; } void SetAttachedControl(Control* new_control) { control_ = new_control; } - WindowHost* GetWindowHost() const { return ui_host_; } + WindowHost* GetWindowHost() const { return window_host_; } RenderObject* GetParent() const { return parent_; } @@ -132,6 +133,11 @@ class RenderObject : public Object { // Add offset before pass point to children. virtual RenderObject* HitTest(const Point& point) = 0; + IEvent* AttachToHostEvent() { return &attach_to_host_event_; } + IEvent* DetachFromHostEvent() { + return &detach_from_host_event_; + } + public: void InvalidateLayout(); void InvalidatePaint(); @@ -190,7 +196,6 @@ class RenderObject : public Object { virtual void OnLayoutContent(const Rect& content_rect) = 0; virtual void OnAfterLayout(); - static void NotifyAfterLayoutRecursive(RenderObject* render_object); virtual Rect GetPaddingRect() const; virtual Rect GetContentRect() const; @@ -198,11 +203,11 @@ class RenderObject : public Object { private: void SetParent(RenderObject* new_parent); - void SetRenderHostRecursive(WindowHost* host); + void SetWindowHostRecursive(WindowHost* host); private: Control* control_ = nullptr; - WindowHost* ui_host_ = nullptr; + WindowHost* window_host_ = nullptr; RenderObject* parent_ = nullptr; std::vector children_{}; @@ -217,5 +222,8 @@ class RenderObject : public Object { Thickness margin_{}; Thickness padding_{}; + + Event attach_to_host_event_; + Event detach_from_host_event_; }; } // namespace cru::ui::render diff --git a/include/cru/ui/render/WindowRenderObject.hpp b/include/cru/ui/render/WindowRenderObject.hpp deleted file mode 100644 index 23fd8748..00000000 --- a/include/cru/ui/render/WindowRenderObject.hpp +++ /dev/null @@ -1,34 +0,0 @@ -#pragma once -#include "RenderObject.hpp" - -#include - -namespace cru::ui::render { -class WindowRenderObject : public RenderObject { - public: - WindowRenderObject(WindowHost* host); - WindowRenderObject(const WindowRenderObject& other) = delete; - WindowRenderObject(WindowRenderObject&& other) = delete; - WindowRenderObject& operator=(const WindowRenderObject& other) = delete; - WindowRenderObject& operator=(WindowRenderObject&& other) = delete; - ~WindowRenderObject() override = default; - - RenderObject* HitTest(const Point& point) override; - - public: - std::u16string_view GetName() const override; - - protected: - Size OnMeasureContent(const MeasureRequirement& requirement, - const MeasureSize& preferred_size) override; - void OnLayoutContent(const Rect& content_rect) override; - - private: - RenderObject* GetChild() const { - return GetChildren().empty() ? nullptr : GetChildren()[0]; - } - - private: - EventRevokerGuard after_layout_event_guard_; -}; -} // namespace cru::ui::render diff --git a/src/ui/CMakeLists.txt b/src/ui/CMakeLists.txt index d59fd7da..045fea24 100644 --- a/src/ui/CMakeLists.txt +++ b/src/ui/CMakeLists.txt @@ -30,7 +30,6 @@ add_library(cru_ui STATIC render/ScrollRenderObject.cpp render/StackLayoutRenderObject.cpp render/TextRenderObject.cpp - render/WindowRenderObject.cpp ) target_sources(cru_ui PUBLIC ${CRU_UI_INCLUDE_DIR}/Base.hpp @@ -63,6 +62,5 @@ target_sources(cru_ui PUBLIC ${CRU_UI_INCLUDE_DIR}/render/ScrollRenderObject.hpp ${CRU_UI_INCLUDE_DIR}/render/StackLayoutRenderObject.hpp ${CRU_UI_INCLUDE_DIR}/render/TextRenderObject.hpp - ${CRU_UI_INCLUDE_DIR}/render/WindowRenderObject.hpp ) target_link_libraries(cru_ui PUBLIC cru_platform_native) diff --git a/src/ui/ContentControl.cpp b/src/ui/ContentControl.cpp index 60d944d6..19b1b06f 100644 --- a/src/ui/ContentControl.cpp +++ b/src/ui/ContentControl.cpp @@ -3,25 +3,19 @@ #include "cru/ui/Window.hpp" namespace cru::ui { -ContentControl::ContentControl() - : child_vector_{nullptr}, child_(child_vector_[0]) {} - -ContentControl::~ContentControl() { delete child_; } +Control* ContentControl::GetChild() const { + if (GetChildren().empty()) return nullptr; + return GetChildren()[0]; +} void ContentControl::SetChild(Control* child) { - Expects(!dynamic_cast(child)); // Can't add a window as child. - if (child == child_) return; - - const auto host = GetWindowHost(); - const auto old_child = child_; - child_ = child; - if (old_child) { - old_child->_SetParent(nullptr); - old_child->_SetDescendantWindowHost(nullptr); + Control* old_child = nullptr; + if (!GetChildren().empty()) { + old_child = GetChildren()[0]; + this->RemoveChild(0); } if (child) { - child->_SetParent(this); - child->_SetDescendantWindowHost(host); + this->AddChild(child, 0); } OnChildChanged(old_child, child); } diff --git a/src/ui/Control.cpp b/src/ui/Control.cpp index cd7ed0dc..13b1c780 100644 --- a/src/ui/Control.cpp +++ b/src/ui/Control.cpp @@ -1,10 +1,12 @@ #include "cru/ui/Control.hpp" +#include "RoutedEventDispatch.hpp" +#include "cru/common/Base.hpp" #include "cru/platform/native/Cursor.hpp" #include "cru/platform/native/UiApplication.hpp" #include "cru/ui/Base.hpp" #include "cru/ui/WindowHost.hpp" -#include "RoutedEventDispatch.hpp" +#include "cru/ui/render/RenderObject.hpp" #include @@ -25,49 +27,16 @@ Control::Control() { }); } -void Control::_SetParent(Control* parent) { - const auto old_parent = GetParent(); - parent_ = parent; - const auto new_parent = GetParent(); - if (old_parent != new_parent) OnParentChanged(old_parent, new_parent); +Control::~Control() { + for (const auto child : children_) delete child; } -void Control::_SetDescendantWindowHost(WindowHost* host) { - if (host == nullptr && ui_host_ == nullptr) return; - - // You can only attach or detach window. - Expects((host != nullptr && ui_host_ == nullptr) || - (host == nullptr && ui_host_ != nullptr)); - - if (host == nullptr) { - const auto old = ui_host_; - TraverseDescendants([old](Control* control) { - control->ui_host_ = nullptr; - control->OnDetachFromHost(old); - }); - } else - TraverseDescendants([host](Control* control) { - control->ui_host_ = host; - control->OnAttachToHost(host); - }); -} +WindowHost* Control::GetWindowHost() const { return window_host_; } void Control::TraverseDescendants( const std::function& predicate) { - _TraverseDescendants(this, predicate); -} - -void Control::_TraverseDescendants( - Control* control, const std::function& predicate) { - predicate(control); - for (auto c : control->GetChildren()) _TraverseDescendants(c, predicate); -} - -bool Control::RequestFocus() { - auto host = GetWindowHost(); - if (host == nullptr) return false; - - return host->RequestFocusFor(this); + predicate(this); + for (auto c : GetChildren()) c->TraverseDescendants(predicate); } bool Control::HasFocus() { @@ -84,6 +53,13 @@ bool Control::CaptureMouse() { return host->CaptureMouseFor(this); } +void Control::SetFocus() { + auto host = GetWindowHost(); + if (host == nullptr) return; + + host->SetFocusControl(this); +} + bool Control::ReleaseMouse() { auto host = GetWindowHost(); if (host == nullptr) return false; @@ -119,6 +95,58 @@ void Control::SetCursor(std::shared_ptr cursor) { } } +void Control::AddChild(Control* control, const Index position) { + Expects(control->GetParent() == + nullptr); // The control already has a parent. + Expects(position >= 0); + Expects(position <= static_cast( + children_.size())); // The position is out of range. + + children_.insert(children_.cbegin() + position, control); + + const auto old_parent = control->parent_; + control->parent_ = this; + + OnAddChild(control, position); + control->OnParentChanged(old_parent, this); + + if (window_host_) + control->TraverseDescendants([this](Control* control) { + control->window_host_ = window_host_; + control->OnAttachToHost(window_host_); + }); +} + +void Control::RemoveChild(const Index position) { + Expects(position >= 0); + Expects(position < static_cast( + children_.size())); // The position is out of range. + + const auto i = children_.cbegin() + position; + const auto control = *i; + + children_.erase(i); + control->parent_ = nullptr; + + OnRemoveChild(control, position); + control->OnParentChanged(this, nullptr); + + if (window_host_) + control->TraverseDescendants([this](Control* control) { + control->window_host_ = nullptr; + control->OnDetachFromHost(window_host_); + }); +} + +void Control::OnAddChild(Control* child, Index position) { + CRU_UNUSED(child) + CRU_UNUSED(position) +} +void Control::OnRemoveChild(Control* child, Index position) { + CRU_UNUSED(child) + CRU_UNUSED(position) +} + void Control::OnParentChanged(Control* old_parent, Control* new_parent) { CRU_UNUSED(old_parent) CRU_UNUSED(new_parent) diff --git a/src/ui/LayoutControl.cpp b/src/ui/LayoutControl.cpp index 05fcdc4a..351026f9 100644 --- a/src/ui/LayoutControl.cpp +++ b/src/ui/LayoutControl.cpp @@ -3,51 +3,4 @@ #include "cru/ui/Window.hpp" namespace cru::ui { -LayoutControl::~LayoutControl() { - for (const auto child : children_) delete child; -} - -void LayoutControl::AddChild(Control* control, const Index position) { - Expects(control->GetParent() == - nullptr); // The control already has a parent. - Expects(!dynamic_cast(control)); // Can't add a window as child. - Expects(position >= 0); - Expects(position <= - static_cast( - this->children_.size())); // The position is out of range. - - children_.insert(this->children_.cbegin() + position, control); - - control->_SetParent(this); - control->_SetDescendantWindowHost(GetWindowHost()); - - OnAddChild(control, position); -} - -void LayoutControl::RemoveChild(const Index position) { - Expects(position >= 0); - Expects(position < - static_cast( - this->children_.size())); // The position is out of range. - - const auto i = children_.cbegin() + position; - const auto child = *i; - - children_.erase(i); - - child->_SetParent(nullptr); - child->_SetDescendantWindowHost(nullptr); - - OnRemoveChild(child, position); -} - -void LayoutControl::OnAddChild(Control* child, const Index position) { - CRU_UNUSED(child) - CRU_UNUSED(position) -} - -void LayoutControl::OnRemoveChild(Control* child, const Index position) { - CRU_UNUSED(child) - CRU_UNUSED(position) -} } // namespace cru::ui diff --git a/src/ui/NoChildControl.cpp b/src/ui/NoChildControl.cpp index 86861049..8adbe3bc 100644 --- a/src/ui/NoChildControl.cpp +++ b/src/ui/NoChildControl.cpp @@ -1,5 +1,3 @@ #include "cru/ui/NoChildControl.hpp" -namespace cru::ui { -const std::vector NoChildControl::empty_control_vector{}; -} +namespace cru::ui {} diff --git a/src/ui/Window.cpp b/src/ui/Window.cpp index a8cb315b..6d507858 100644 --- a/src/ui/Window.cpp +++ b/src/ui/Window.cpp @@ -1,28 +1,31 @@ #include "cru/ui/Window.hpp" -#include "cru/ui/render/WindowRenderObject.hpp" +#include "cru/common/Base.hpp" #include "cru/ui/WindowHost.hpp" +#include "cru/ui/render/Base.hpp" +#include "cru/ui/render/StackLayoutRenderObject.hpp" namespace cru::ui { -Window* Window::CreateOverlapped() { - return new Window(tag_overlapped_constructor{}); -} +Window* Window::CreateOverlapped() { return new Window(); } -Window::Window(tag_overlapped_constructor) { - managed_ui_host_ = std::make_unique(this); +Window::Window() : render_object_(new render::StackLayoutRenderObject()) { + window_host_ = std::make_unique(this); } -Window::~Window() { - // explicit destroy ui host first. - managed_ui_host_.reset(); -} +Window::~Window() {} std::u16string_view Window::GetControlType() const { return control_type; } -render::RenderObject* Window::GetRenderObject() const { return render_object_; } +render::RenderObject* Window::GetRenderObject() const { + return render_object_.get(); +} + +void Window::OnAddChild(Control* child, Index position) { + render_object_->AddChild(child->GetRenderObject(), position); +} -void Window::OnChildChanged(Control* old_child, Control* new_child) { - if (old_child) render_object_->RemoveChild(0); - if (new_child) render_object_->AddChild(new_child->GetRenderObject(), 0); +void Window::OnRemoveChild(Control* child, Index position) { + CRU_UNUSED(child); + render_object_->RemoveChild(position); } } // namespace cru::ui diff --git a/src/ui/WindowHost.cpp b/src/ui/WindowHost.cpp index d3dec422..1dba4404 100644 --- a/src/ui/WindowHost.cpp +++ b/src/ui/WindowHost.cpp @@ -9,7 +9,9 @@ #include "cru/ui/DebugFlags.hpp" #include "cru/ui/Window.hpp" #include "cru/ui/render/MeasureRequirement.hpp" -#include "cru/ui/render/WindowRenderObject.hpp" +#include "cru/ui/render/RenderObject.hpp" + +#include namespace cru::ui { using platform::native::INativeWindow; @@ -97,25 +99,18 @@ inline void BindNativeEvent( } } // namespace -WindowHost::WindowHost(Window* window) - : window_control_(window), - mouse_hover_control_(nullptr), - focus_control_(window), - mouse_captured_control_(nullptr) { +WindowHost::WindowHost(Control* root_control) : root_control_(root_control) { const auto ui_application = IUiApplication::GetInstance(); - native_window_resolver_ = ui_application->CreateWindow(nullptr); - - const auto native_window = native_window_resolver_->Resolve(); - - auto input_method_context = - ui_application->GetInputMethodManager()->GetContext(native_window); - input_method_context->DisableIME(); + auto native_window = ui_application->CreateWindow(nullptr); + native_window_ = native_window; - window->ui_host_ = this; + root_control_->TraverseDescendants([this](Control* control) { + control->window_host_ = this; + control->OnAttachToHost(this); + }); - root_render_object_ = std::make_unique(this); - root_render_object_->SetAttachedControl(window); - window->render_object_ = root_render_object_.get(); + root_render_object_ = root_control->GetRenderObject(); + root_render_object_->SetWindowHostRecursive(this); BindNativeEvent(this, native_window, native_window->DestroyEvent(), &WindowHost::OnNativeDestroy, event_revoker_guards_); @@ -140,34 +135,24 @@ WindowHost::WindowHost(Window* window) } WindowHost::~WindowHost() { - deleting_ = true; - window_control_->TraverseDescendants( - [this](Control* control) { control->OnDetachFromHost(this); }); - if (!native_window_destroyed_) { - const auto native_window = native_window_resolver_->Resolve(); - if (native_window) { - native_window->Close(); - } + if (native_window_) { + native_window_->Close(); } } void WindowHost::InvalidatePaint() { - if (const auto native_window = native_window_resolver_->Resolve()) - native_window->RequestRepaint(); + if (native_window_) native_window_->RequestRepaint(); } void WindowHost::InvalidateLayout() { if constexpr (debug_flags::layout) log::TagDebug(log_tag, u"A relayout is requested."); if (!need_layout_) { - platform::native::IUiApplication::GetInstance()->SetImmediate( - [resolver = this->CreateResolver()] { - if (const auto host = resolver.Resolve()) { - host->Relayout(); - host->need_layout_ = false; - host->InvalidatePaint(); - } - }); + platform::native::IUiApplication::GetInstance()->SetImmediate([this] { + Relayout(); + need_layout_ = false; + InvalidatePaint(); + }); need_layout_ = true; } } @@ -183,15 +168,17 @@ void WindowHost::SetLayoutPreferToFillWindow(bool value) { } void WindowHost::Relayout() { - const auto native_window = native_window_resolver_->Resolve(); - const auto client_size = native_window - ? native_window->GetClientSize() - : Size{100, 100}; // a reasonable assumed size + const auto available_size = + native_window_ ? native_window_->GetClientSize() + : Size{100, 100}; // a reasonable assumed size + Relayout(available_size); +} +void WindowHost::Relayout(const Size& available_size) { root_render_object_->Measure( - render::MeasureRequirement{client_size, + render::MeasureRequirement{available_size, IsLayoutPreferToFillWindow() - ? render::MeasureSize(client_size) + ? render::MeasureSize(available_size) : render::MeasureSize::NotSpecified()}, render::MeasureSize::NotSpecified()); root_render_object_->Layout(Point{}); @@ -202,11 +189,11 @@ void WindowHost::Relayout() { log::TagDebug(log_tag, u"A relayout is finished."); } -bool WindowHost::RequestFocusFor(Control* control) { - Expects(control != nullptr); // The control to request focus can't be null. - // You can set it as the window. +Control* WindowHost::GetFocusControl() { return focus_control_; } - if (focus_control_ == control) return true; +void WindowHost::SetFocusControl(Control* control) { + if (focus_control_ == control) return; + if (control == nullptr) control = root_control_; const auto old_focus_control = focus_control_; @@ -217,15 +204,10 @@ bool WindowHost::RequestFocusFor(Control* control) { DispatchEvent(event_names::GainFocus, control, &Control::GainFocusEvent, nullptr, false); - - return true; } -Control* WindowHost::GetFocusControl() { return focus_control_; } - bool WindowHost::CaptureMouseFor(Control* control) { - const auto native_window = native_window_resolver_->Resolve(); - if (!native_window) return false; + if (!native_window_) return false; if (control == mouse_captured_control_) return true; @@ -236,7 +218,7 @@ bool WindowHost::CaptureMouseFor(Control* control) { if (old_capture_control != mouse_hover_control_) { DispatchMouseHoverControlChangeEvent( old_capture_control, mouse_hover_control_, - native_window->GetMousePosition(), true, false); + native_window_->GetMousePosition(), true, false); } UpdateCursor(); return true; @@ -247,7 +229,7 @@ bool WindowHost::CaptureMouseFor(Control* control) { mouse_captured_control_ = control; DispatchMouseHoverControlChangeEvent( mouse_hover_control_, mouse_captured_control_, - native_window->GetMousePosition(), false, true); + native_window_->GetMousePosition(), false, true); UpdateCursor(); return true; } @@ -266,8 +248,8 @@ void WindowHost::RunAfterLayoutStable(std::function action) { void WindowHost::OnNativeDestroy(INativeWindow* window, std::nullptr_t) { CRU_UNUSED(window) - native_window_destroyed_ = true; - if (!deleting_ && !retain_after_destroy_) delete window_control_; + this->relayout_timer_canceler_.Reset(); + this->native_window_ = nullptr; } void WindowHost::OnNativePaint(INativeWindow* window, std::nullptr_t) { @@ -399,9 +381,9 @@ void WindowHost::DispatchMouseHoverControlChangeEvent(Control* old_control, } void WindowHost::UpdateCursor() { - if (const auto native_window = native_window_resolver_->Resolve()) { + if (native_window_) { const auto capture = GetMouseCaptureControl(); - native_window->SetCursor( + native_window_->SetCursor( (capture ? capture : GetMouseHoverControl())->GetInheritedCursor()); } } @@ -413,6 +395,6 @@ Control* WindowHost::HitTest(const Point& point) { Ensures(control); return control; } - return window_control_; + return root_control_; } } // namespace cru::ui diff --git a/src/ui/controls/TextControlService.hpp b/src/ui/controls/TextControlService.hpp index 8c1bd32f..33a6bc36 100644 --- a/src/ui/controls/TextControlService.hpp +++ b/src/ui/controls/TextControlService.hpp @@ -61,7 +61,7 @@ class TextControlService : public Object { void SetEditable(bool editable) { this->editable_ = editable; - this->input_method_context_.reset(); + if (!editable) CancelComposition(); } std::u16string GetText() { return this->text_; } @@ -69,8 +69,8 @@ class TextControlService : public Object { void SetText(std::u16string text, bool stop_composition = false) { this->text_ = std::move(text); CoerceSelection(); - if (stop_composition && this->input_method_context_) { - this->input_method_context_->CancelComposition(); + if (stop_composition) { + CancelComposition(); } SyncTextRenderObject(); } @@ -83,8 +83,8 @@ class TextControlService : public Object { } this->text_.insert(this->text_.cbegin() + position, text.begin(), text.end()); - if (stop_composition && this->input_method_context_) { - this->input_method_context_->CancelComposition(); + if (stop_composition) { + CancelComposition(); } SyncTextRenderObject(); } @@ -129,15 +129,30 @@ class TextControlService : public Object { this->text_.erase(this->text_.cbegin() + range.GetStart(), this->text_.cbegin() + range.GetEnd()); this->CoerceSelection(); - if (stop_composition && this->input_method_context_) { - this->input_method_context_->CancelComposition(); + if (stop_composition) { + CancelComposition(); } this->SyncTextRenderObject(); } + platform::native::IInputMethodContext* GetInputMethodContext() { + WindowHost* host = this->control_->GetWindowHost(); + if (!host) return nullptr; + platform::native::INativeWindow* native_window = host->GetNativeWindow(); + if (!native_window) return nullptr; + return native_window->GetInputMethodContext(); + } + + void CancelComposition() { + auto input_method_context = GetInputMethodContext(); + if (input_method_context == nullptr) return; + input_method_context->CancelComposition(); + } + std::optional GetCompositionInfo() { - if (this->input_method_context_ == nullptr) return std::nullopt; - auto composition_info = this->input_method_context_->GetCompositionText(); + auto input_method_context = GetInputMethodContext(); + if (input_method_context == nullptr) return std::nullopt; + auto composition_info = input_method_context->GetCompositionText(); if (composition_info.text.empty()) return std::nullopt; return composition_info; } @@ -319,12 +334,11 @@ class TextControlService : public Object { } void MouseDownHandler(event::MouseButtonEventArgs& args) { - this->control_->RequestFocus(); if (this->select_down_button_.has_value()) { return; } else { + this->control_->SetFocus(); if (!this->control_->CaptureMouse()) return; - if (!this->control_->RequestFocus()) return; const auto text_render_object = this->GetTextRenderObject(); this->select_down_button_ = args.GetButton(); const auto result = text_render_object->TextHitTest( @@ -408,33 +422,35 @@ class TextControlService : public Object { void GainFocusHandler(event::FocusChangeEventArgs& args) { CRU_UNUSED(args); if (editable_) { - WindowHost* ui_host = this->control_->GetWindowHost(); - auto window = ui_host->GetNativeWindowResolver()->Resolve(); - if (window == nullptr) return; - input_method_context_ = - GetUiApplication()->GetInputMethodManager()->GetContext(window); - input_method_context_->EnableIME(); + auto input_method_context = GetInputMethodContext(); + if (input_method_context == nullptr) return; + input_method_context->EnableIME(); auto sync = [this](std::nullptr_t) { this->SyncTextRenderObject(); ScrollToCaret(); }; - input_method_context_->CompositionStartEvent()->AddHandler( - [this](std::nullptr_t) { this->DeleteSelectedText(); }); - input_method_context_->CompositionEvent()->AddHandler(sync); - input_method_context_->CompositionEndEvent()->AddHandler(sync); - input_method_context_->TextEvent()->AddHandler( - [this](const std::u16string_view& text) { - if (text == u"\b") return; - this->ReplaceSelectedText(text); - }); + input_method_context_event_guard_ += + input_method_context->CompositionStartEvent()->AddHandler( + [this](std::nullptr_t) { this->DeleteSelectedText(); }); + input_method_context_event_guard_ += + input_method_context->CompositionEvent()->AddHandler(sync); + input_method_context_event_guard_ += + input_method_context->CompositionEndEvent()->AddHandler(sync); + input_method_context_event_guard_ += + input_method_context->TextEvent()->AddHandler( + [this](const std::u16string_view& text) { + if (text == u"\b") return; + this->ReplaceSelectedText(text); + }); } } void LoseFocusHandler(event::FocusChangeEventArgs& args) { if (!args.IsWindow()) this->AbortSelection(); - if (input_method_context_) { - input_method_context_->DisableIME(); - input_method_context_.reset(); + input_method_context_event_guard_.Clear(); + auto input_method_context = GetInputMethodContext(); + if (input_method_context) { + input_method_context->DisableIME(); } SyncTextRenderObject(); } @@ -442,6 +458,7 @@ class TextControlService : public Object { private: gsl::not_null control_; EventRevokerListGuard event_guard_; + EventRevokerListGuard input_method_context_event_guard_; std::u16string text_; TextRange selection_; @@ -457,7 +474,5 @@ class TextControlService : public Object { // nullopt means not selecting std::optional select_down_button_; - - std::unique_ptr input_method_context_; }; // namespace cru::ui::controls } // namespace cru::ui::controls diff --git a/src/ui/render/RenderObject.cpp b/src/ui/render/RenderObject.cpp index 5266daaf..fd0c7712 100644 --- a/src/ui/render/RenderObject.cpp +++ b/src/ui/render/RenderObject.cpp @@ -24,7 +24,7 @@ void RenderObject::AddChild(RenderObject* render_object, const Index position) { children_.insert(children_.cbegin() + position, render_object); render_object->SetParent(this); - render_object->SetRenderHostRecursive(GetWindowHost()); + render_object->SetWindowHostRecursive(GetWindowHost()); OnAddChild(render_object, position); } @@ -37,7 +37,7 @@ void RenderObject::RemoveChild(const Index position) { const auto removed_child = *i; children_.erase(i); removed_child->SetParent(nullptr); - removed_child->SetRenderHostRecursive(nullptr); + removed_child->SetWindowHostRecursive(nullptr); OnRemoveChild(removed_child, position); } @@ -269,11 +269,11 @@ void RenderObject::SetParent(RenderObject* new_parent) { } void RenderObject::InvalidateLayout() { - if (ui_host_ != nullptr) ui_host_->InvalidateLayout(); + if (window_host_ != nullptr) window_host_->InvalidateLayout(); } void RenderObject::InvalidatePaint() { - if (ui_host_ != nullptr) ui_host_->InvalidatePaint(); + if (window_host_ != nullptr) window_host_->InvalidatePaint(); } constexpr std::u16string_view kUnamedName(u"UNNAMED"); @@ -297,17 +297,16 @@ std::u16string RenderObject::GetDebugPathInTree() const { return result; } -void RenderObject::NotifyAfterLayoutRecursive(RenderObject* render_object) { - render_object->OnAfterLayout(); - for (const auto o : render_object->GetChildren()) { - NotifyAfterLayoutRecursive(o); +void RenderObject::SetWindowHostRecursive(WindowHost* host) { + if (window_host_ != nullptr) { + detach_from_host_event_.Raise(nullptr); + } + window_host_ = host; + if (host != nullptr) { + attach_to_host_event_.Raise(nullptr); } -} - -void RenderObject::SetRenderHostRecursive(WindowHost* host) { - ui_host_ = host; for (const auto child : GetChildren()) { - child->SetRenderHostRecursive(host); + child->SetWindowHostRecursive(host); } } } // namespace cru::ui::render diff --git a/src/ui/render/WindowRenderObject.cpp b/src/ui/render/WindowRenderObject.cpp deleted file mode 100644 index 23cca12e..00000000 --- a/src/ui/render/WindowRenderObject.cpp +++ /dev/null @@ -1,44 +0,0 @@ -#include "cru/ui/render/WindowRenderObject.hpp" - -#include "../Helper.hpp" -#include "cru/platform/graph/util/Painter.hpp" -#include "cru/ui/WindowHost.hpp" - -namespace cru::ui::render { -WindowRenderObject::WindowRenderObject(WindowHost* host) { - SetChildMode(ChildMode::Single); - ui_host_ = host; - after_layout_event_guard_.Reset(host->AfterLayoutEvent()->AddHandler( - [this](auto) { NotifyAfterLayoutRecursive(this); })); -} - -RenderObject* WindowRenderObject::HitTest(const Point& point) { - if (const auto child = GetChild()) { - auto offset = child->GetOffset(); - Point p{point.x - offset.x, point.y - offset.y}; - const auto result = child->HitTest(p); - if (result != nullptr) { - return result; - } - } - return Rect{Point{}, GetSize()}.IsPointInside(point) ? this : nullptr; -} - -std::u16string_view WindowRenderObject::GetName() const { - return u"WindowRenderObject"; -} - -Size WindowRenderObject::OnMeasureContent(const MeasureRequirement& requirement, - const MeasureSize& preferred_size) { - if (const auto child = GetChild()) { - child->Measure(requirement, preferred_size); - return child->GetSize(); - } else { - return Size{}; - } -} - -void WindowRenderObject::OnLayoutContent(const Rect& content_rect) { - if (const auto child = GetChild()) child->Layout(content_rect.GetLeftTop()); -} -} // namespace cru::ui::render diff --git a/src/win/native/UiApplication.cpp b/src/win/native/UiApplication.cpp index 60ff8e8c..87ef0b81 100644 --- a/src/win/native/UiApplication.cpp +++ b/src/win/native/UiApplication.cpp @@ -43,7 +43,6 @@ WinUiApplication::WinUiApplication() { timer_manager_ = std::make_unique(god_window_.get()); window_manager_ = std::make_unique(this); cursor_manager_ = std::make_unique(); - input_method_manager_ = std::make_unique(this); } WinUiApplication::~WinUiApplication() { instance = nullptr; } @@ -116,8 +115,4 @@ cru::platform::graph::IGraphFactory* WinUiApplication::GetGraphFactory() { ICursorManager* WinUiApplication::GetCursorManager() { return cursor_manager_.get(); } - -IInputMethodManager* WinUiApplication::GetInputMethodManager() { - return input_method_manager_.get(); -} } // namespace cru::platform::native::win diff --git a/src/win/native/Window.cpp b/src/win/native/Window.cpp index d9237c4f..1a6fcb07 100644 --- a/src/win/native/Window.cpp +++ b/src/win/native/Window.cpp @@ -55,6 +55,7 @@ WinNativeWindow::WinNativeWindow(WinUiApplication* application, window_render_target_->SetDpi(dpi_, dpi_); input_method_context_ = std::make_unique(this); + input_method_context_->DisableIME(); } WinNativeWindow::~WinNativeWindow() { -- cgit v1.2.3 From 6aa2201797a9ed64ce0178215ae941d0c5f09579 Mon Sep 17 00:00:00 2001 From: crupest Date: Fri, 30 Oct 2020 00:07:57 +0800 Subject: ... --- demos/CMakeLists.txt | 2 +- demos/input_method/main.cpp | 16 +- demos/main/main.cpp | 6 +- include/cru/platform/graph/Base.hpp | 24 -- include/cru/platform/graph/Brush.hpp | 11 - include/cru/platform/graph/Factory.hpp | 25 -- include/cru/platform/graph/Font.hpp | 8 - include/cru/platform/graph/Geometry.hpp | 20 - include/cru/platform/graph/Painter.hpp | 29 -- include/cru/platform/graph/Resource.hpp | 10 - include/cru/platform/graph/TextLayout.hpp | 24 -- include/cru/platform/graph/util/Painter.hpp | 17 - include/cru/platform/graphics/Base.hpp | 24 ++ include/cru/platform/graphics/Brush.hpp | 11 + include/cru/platform/graphics/Factory.hpp | 25 ++ include/cru/platform/graphics/Font.hpp | 8 + include/cru/platform/graphics/Geometry.hpp | 20 + include/cru/platform/graphics/Painter.hpp | 29 ++ include/cru/platform/graphics/Resource.hpp | 10 + include/cru/platform/graphics/TextLayout.hpp | 24 ++ include/cru/platform/graphics/util/Painter.hpp | 17 + include/cru/platform/gui/Base.hpp | 47 +++ include/cru/platform/gui/Cursor.hpp | 14 + include/cru/platform/gui/InputMethod.hpp | 80 ++++ include/cru/platform/gui/Keyboard.hpp | 127 ++++++ include/cru/platform/gui/UiApplication.hpp | 109 +++++ include/cru/platform/gui/Window.hpp | 57 +++ include/cru/platform/native/Base.hpp | 47 --- include/cru/platform/native/Cursor.hpp | 14 - include/cru/platform/native/InputMethod.hpp | 80 ---- include/cru/platform/native/Keyboard.hpp | 127 ------ include/cru/platform/native/UiApplication.hpp | 109 ----- include/cru/platform/native/Window.hpp | 57 --- include/cru/ui/Base.hpp | 20 +- include/cru/ui/Control.hpp | 8 +- include/cru/ui/ShortcutHub.hpp | 22 +- include/cru/ui/UiEvent.hpp | 30 +- include/cru/ui/UiManager.hpp | 8 +- include/cru/ui/WindowHost.hpp | 42 +- include/cru/ui/render/BorderRenderObject.hpp | 26 +- include/cru/ui/render/CanvasRenderObject.hpp | 2 +- include/cru/ui/render/LayoutRenderObject.hpp | 2 +- include/cru/ui/render/RenderObject.hpp | 12 +- include/cru/ui/render/ScrollRenderObject.hpp | 4 +- include/cru/ui/render/TextRenderObject.hpp | 38 +- include/cru/win/graph/direct/Brush.hpp | 39 -- include/cru/win/graph/direct/ComResource.hpp | 11 - include/cru/win/graph/direct/ConvertUtil.hpp | 107 ----- include/cru/win/graph/direct/Exception.hpp | 7 - include/cru/win/graph/direct/Factory.hpp | 58 --- include/cru/win/graph/direct/Font.hpp | 33 -- include/cru/win/graph/direct/Geometry.hpp | 57 --- include/cru/win/graph/direct/Painter.hpp | 60 --- include/cru/win/graph/direct/Resource.hpp | 49 --- include/cru/win/graph/direct/TextLayout.hpp | 55 --- include/cru/win/graph/direct/WindowPainter.hpp | 21 - .../cru/win/graph/direct/WindowRenderTarget.hpp | 42 -- include/cru/win/graphics/direct/Brush.hpp | 39 ++ include/cru/win/graphics/direct/ComResource.hpp | 11 + include/cru/win/graphics/direct/ConvertUtil.hpp | 107 +++++ include/cru/win/graphics/direct/Exception.hpp | 7 + include/cru/win/graphics/direct/Factory.hpp | 58 +++ include/cru/win/graphics/direct/Font.hpp | 33 ++ include/cru/win/graphics/direct/Geometry.hpp | 57 +++ include/cru/win/graphics/direct/Painter.hpp | 60 +++ include/cru/win/graphics/direct/Resource.hpp | 49 +++ include/cru/win/graphics/direct/TextLayout.hpp | 55 +++ include/cru/win/graphics/direct/WindowPainter.hpp | 21 + .../cru/win/graphics/direct/WindowRenderTarget.hpp | 42 ++ include/cru/win/gui/Base.hpp | 16 + include/cru/win/gui/Cursor.hpp | 49 +++ include/cru/win/gui/Exception.hpp | 7 + include/cru/win/gui/GodWindow.hpp | 38 ++ include/cru/win/gui/InputMethod.hpp | 87 ++++ include/cru/win/gui/Keyboard.hpp | 9 + include/cru/win/gui/Resource.hpp | 23 ++ include/cru/win/gui/UiApplication.hpp | 74 ++++ include/cru/win/gui/Window.hpp | 178 ++++++++ include/cru/win/gui/WindowClass.hpp | 24 ++ .../cru/win/gui/WindowNativeMessageEventArgs.hpp | 40 ++ include/cru/win/native/Base.hpp | 16 - include/cru/win/native/Cursor.hpp | 49 --- include/cru/win/native/Exception.hpp | 7 - include/cru/win/native/GodWindow.hpp | 38 -- include/cru/win/native/InputMethod.hpp | 87 ---- include/cru/win/native/Keyboard.hpp | 9 - include/cru/win/native/Resource.hpp | 23 -- include/cru/win/native/UiApplication.hpp | 74 ---- include/cru/win/native/Window.hpp | 178 -------- include/cru/win/native/WindowClass.hpp | 24 -- .../win/native/WindowNativeMessageEventArgs.hpp | 40 -- src/platform/CMakeLists.txt | 4 +- src/platform/graph/CMakeLists.txt | 14 - src/platform/graphics/CMakeLists.txt | 14 + src/platform/gui/CMakeLists.txt | 14 + src/platform/gui/Keyboard.cpp | 142 +++++++ src/platform/gui/UiApplication.cpp | 15 + src/platform/native/CMakeLists.txt | 14 - src/platform/native/Keyboard.cpp | 142 ------- src/platform/native/UiApplication.cpp | 15 - src/ui/CMakeLists.txt | 2 +- src/ui/Control.cpp | 10 +- src/ui/Helper.cpp | 8 +- src/ui/Helper.hpp | 4 +- src/ui/UiManager.cpp | 12 +- src/ui/WindowHost.cpp | 30 +- src/ui/controls/Button.cpp | 10 +- src/ui/controls/Container.cpp | 2 +- src/ui/controls/TextControlService.hpp | 22 +- src/ui/render/BorderRenderObject.cpp | 12 +- src/ui/render/CanvasRenderObject.cpp | 2 +- src/ui/render/FlexLayoutRenderObject.cpp | 2 +- src/ui/render/RenderObject.cpp | 16 +- src/ui/render/ScrollRenderObject.cpp | 10 +- src/ui/render/TextRenderObject.cpp | 28 +- src/win/CMakeLists.txt | 4 +- src/win/graph/CMakeLists.txt | 1 - src/win/graph/direct/Brush.cpp | 17 - src/win/graph/direct/CMakeLists.txt | 29 -- src/win/graph/direct/Factory.cpp | 107 ----- src/win/graph/direct/Font.cpp | 31 -- src/win/graph/direct/Geometry.cpp | 62 --- src/win/graph/direct/Painter.cpp | 104 ----- src/win/graph/direct/Resource.cpp | 12 - src/win/graph/direct/TextLayout.cpp | 124 ------ src/win/graph/direct/WindowPainter.cpp | 20 - src/win/graph/direct/WindowRenderTarget.cpp | 81 ---- src/win/graphics/CMakeLists.txt | 1 + src/win/graphics/direct/Brush.cpp | 17 + src/win/graphics/direct/CMakeLists.txt | 29 ++ src/win/graphics/direct/Factory.cpp | 107 +++++ src/win/graphics/direct/Font.cpp | 31 ++ src/win/graphics/direct/Geometry.cpp | 62 +++ src/win/graphics/direct/Painter.cpp | 104 +++++ src/win/graphics/direct/Resource.cpp | 12 + src/win/graphics/direct/TextLayout.cpp | 124 ++++++ src/win/graphics/direct/WindowPainter.cpp | 20 + src/win/graphics/direct/WindowRenderTarget.cpp | 81 ++++ src/win/gui/CMakeLists.txt | 31 ++ src/win/gui/Cursor.cpp | 51 +++ src/win/gui/GodWindow.cpp | 63 +++ src/win/gui/InputMethod.cpp | 278 +++++++++++++ src/win/gui/Keyboard.cpp | 74 ++++ src/win/gui/TimerManager.cpp | 100 +++++ src/win/gui/TimerManager.hpp | 61 +++ src/win/gui/UiApplication.cpp | 118 ++++++ src/win/gui/Window.cpp | 453 +++++++++++++++++++++ src/win/gui/WindowClass.cpp | 28 ++ src/win/gui/WindowManager.cpp | 56 +++ src/win/gui/WindowManager.hpp | 51 +++ src/win/native/CMakeLists.txt | 31 -- src/win/native/Cursor.cpp | 51 --- src/win/native/GodWindow.cpp | 63 --- src/win/native/InputMethod.cpp | 278 ------------- src/win/native/Keyboard.cpp | 74 ---- src/win/native/TimerManager.cpp | 100 ----- src/win/native/TimerManager.hpp | 61 --- src/win/native/UiApplication.cpp | 118 ------ src/win/native/Window.cpp | 453 --------------------- src/win/native/WindowClass.cpp | 28 -- src/win/native/WindowManager.cpp | 56 --- src/win/native/WindowManager.hpp | 51 --- 162 files changed, 4031 insertions(+), 4031 deletions(-) delete mode 100644 include/cru/platform/graph/Base.hpp delete mode 100644 include/cru/platform/graph/Brush.hpp delete mode 100644 include/cru/platform/graph/Factory.hpp delete mode 100644 include/cru/platform/graph/Font.hpp delete mode 100644 include/cru/platform/graph/Geometry.hpp delete mode 100644 include/cru/platform/graph/Painter.hpp delete mode 100644 include/cru/platform/graph/Resource.hpp delete mode 100644 include/cru/platform/graph/TextLayout.hpp delete mode 100644 include/cru/platform/graph/util/Painter.hpp create mode 100644 include/cru/platform/graphics/Base.hpp create mode 100644 include/cru/platform/graphics/Brush.hpp create mode 100644 include/cru/platform/graphics/Factory.hpp create mode 100644 include/cru/platform/graphics/Font.hpp create mode 100644 include/cru/platform/graphics/Geometry.hpp create mode 100644 include/cru/platform/graphics/Painter.hpp create mode 100644 include/cru/platform/graphics/Resource.hpp create mode 100644 include/cru/platform/graphics/TextLayout.hpp create mode 100644 include/cru/platform/graphics/util/Painter.hpp create mode 100644 include/cru/platform/gui/Base.hpp create mode 100644 include/cru/platform/gui/Cursor.hpp create mode 100644 include/cru/platform/gui/InputMethod.hpp create mode 100644 include/cru/platform/gui/Keyboard.hpp create mode 100644 include/cru/platform/gui/UiApplication.hpp create mode 100644 include/cru/platform/gui/Window.hpp delete mode 100644 include/cru/platform/native/Base.hpp delete mode 100644 include/cru/platform/native/Cursor.hpp delete mode 100644 include/cru/platform/native/InputMethod.hpp delete mode 100644 include/cru/platform/native/Keyboard.hpp delete mode 100644 include/cru/platform/native/UiApplication.hpp delete mode 100644 include/cru/platform/native/Window.hpp delete mode 100644 include/cru/win/graph/direct/Brush.hpp delete mode 100644 include/cru/win/graph/direct/ComResource.hpp delete mode 100644 include/cru/win/graph/direct/ConvertUtil.hpp delete mode 100644 include/cru/win/graph/direct/Exception.hpp delete mode 100644 include/cru/win/graph/direct/Factory.hpp delete mode 100644 include/cru/win/graph/direct/Font.hpp delete mode 100644 include/cru/win/graph/direct/Geometry.hpp delete mode 100644 include/cru/win/graph/direct/Painter.hpp delete mode 100644 include/cru/win/graph/direct/Resource.hpp delete mode 100644 include/cru/win/graph/direct/TextLayout.hpp delete mode 100644 include/cru/win/graph/direct/WindowPainter.hpp delete mode 100644 include/cru/win/graph/direct/WindowRenderTarget.hpp create mode 100644 include/cru/win/graphics/direct/Brush.hpp create mode 100644 include/cru/win/graphics/direct/ComResource.hpp create mode 100644 include/cru/win/graphics/direct/ConvertUtil.hpp create mode 100644 include/cru/win/graphics/direct/Exception.hpp create mode 100644 include/cru/win/graphics/direct/Factory.hpp create mode 100644 include/cru/win/graphics/direct/Font.hpp create mode 100644 include/cru/win/graphics/direct/Geometry.hpp create mode 100644 include/cru/win/graphics/direct/Painter.hpp create mode 100644 include/cru/win/graphics/direct/Resource.hpp create mode 100644 include/cru/win/graphics/direct/TextLayout.hpp create mode 100644 include/cru/win/graphics/direct/WindowPainter.hpp create mode 100644 include/cru/win/graphics/direct/WindowRenderTarget.hpp create mode 100644 include/cru/win/gui/Base.hpp create mode 100644 include/cru/win/gui/Cursor.hpp create mode 100644 include/cru/win/gui/Exception.hpp create mode 100644 include/cru/win/gui/GodWindow.hpp create mode 100644 include/cru/win/gui/InputMethod.hpp create mode 100644 include/cru/win/gui/Keyboard.hpp create mode 100644 include/cru/win/gui/Resource.hpp create mode 100644 include/cru/win/gui/UiApplication.hpp create mode 100644 include/cru/win/gui/Window.hpp create mode 100644 include/cru/win/gui/WindowClass.hpp create mode 100644 include/cru/win/gui/WindowNativeMessageEventArgs.hpp delete mode 100644 include/cru/win/native/Base.hpp delete mode 100644 include/cru/win/native/Cursor.hpp delete mode 100644 include/cru/win/native/Exception.hpp delete mode 100644 include/cru/win/native/GodWindow.hpp delete mode 100644 include/cru/win/native/InputMethod.hpp delete mode 100644 include/cru/win/native/Keyboard.hpp delete mode 100644 include/cru/win/native/Resource.hpp delete mode 100644 include/cru/win/native/UiApplication.hpp delete mode 100644 include/cru/win/native/Window.hpp delete mode 100644 include/cru/win/native/WindowClass.hpp delete mode 100644 include/cru/win/native/WindowNativeMessageEventArgs.hpp delete mode 100644 src/platform/graph/CMakeLists.txt create mode 100644 src/platform/graphics/CMakeLists.txt create mode 100644 src/platform/gui/CMakeLists.txt create mode 100644 src/platform/gui/Keyboard.cpp create mode 100644 src/platform/gui/UiApplication.cpp delete mode 100644 src/platform/native/CMakeLists.txt delete mode 100644 src/platform/native/Keyboard.cpp delete mode 100644 src/platform/native/UiApplication.cpp delete mode 100644 src/win/graph/CMakeLists.txt delete mode 100644 src/win/graph/direct/Brush.cpp delete mode 100644 src/win/graph/direct/CMakeLists.txt delete mode 100644 src/win/graph/direct/Factory.cpp delete mode 100644 src/win/graph/direct/Font.cpp delete mode 100644 src/win/graph/direct/Geometry.cpp delete mode 100644 src/win/graph/direct/Painter.cpp delete mode 100644 src/win/graph/direct/Resource.cpp delete mode 100644 src/win/graph/direct/TextLayout.cpp delete mode 100644 src/win/graph/direct/WindowPainter.cpp delete mode 100644 src/win/graph/direct/WindowRenderTarget.cpp create mode 100644 src/win/graphics/CMakeLists.txt create mode 100644 src/win/graphics/direct/Brush.cpp create mode 100644 src/win/graphics/direct/CMakeLists.txt create mode 100644 src/win/graphics/direct/Factory.cpp create mode 100644 src/win/graphics/direct/Font.cpp create mode 100644 src/win/graphics/direct/Geometry.cpp create mode 100644 src/win/graphics/direct/Painter.cpp create mode 100644 src/win/graphics/direct/Resource.cpp create mode 100644 src/win/graphics/direct/TextLayout.cpp create mode 100644 src/win/graphics/direct/WindowPainter.cpp create mode 100644 src/win/graphics/direct/WindowRenderTarget.cpp create mode 100644 src/win/gui/CMakeLists.txt create mode 100644 src/win/gui/Cursor.cpp create mode 100644 src/win/gui/GodWindow.cpp create mode 100644 src/win/gui/InputMethod.cpp create mode 100644 src/win/gui/Keyboard.cpp create mode 100644 src/win/gui/TimerManager.cpp create mode 100644 src/win/gui/TimerManager.hpp create mode 100644 src/win/gui/UiApplication.cpp create mode 100644 src/win/gui/Window.cpp create mode 100644 src/win/gui/WindowClass.cpp create mode 100644 src/win/gui/WindowManager.cpp create mode 100644 src/win/gui/WindowManager.hpp delete mode 100644 src/win/native/CMakeLists.txt delete mode 100644 src/win/native/Cursor.cpp delete mode 100644 src/win/native/GodWindow.cpp delete mode 100644 src/win/native/InputMethod.cpp delete mode 100644 src/win/native/Keyboard.cpp delete mode 100644 src/win/native/TimerManager.cpp delete mode 100644 src/win/native/TimerManager.hpp delete mode 100644 src/win/native/UiApplication.cpp delete mode 100644 src/win/native/Window.cpp delete mode 100644 src/win/native/WindowClass.cpp delete mode 100644 src/win/native/WindowManager.cpp delete mode 100644 src/win/native/WindowManager.hpp (limited to 'demos/main/main.cpp') diff --git a/demos/CMakeLists.txt b/demos/CMakeLists.txt index 64612bf9..16159d08 100644 --- a/demos/CMakeLists.txt +++ b/demos/CMakeLists.txt @@ -1,7 +1,7 @@ add_library(cru_demo_base INTERFACE) if(WIN32) - target_link_libraries(cru_demo_base INTERFACE cru_win_native) + target_link_libraries(cru_demo_base INTERFACE cru_win_gui) endif() add_subdirectory(main) diff --git a/demos/input_method/main.cpp b/demos/input_method/main.cpp index 06098253..5a6dc942 100644 --- a/demos/input_method/main.cpp +++ b/demos/input_method/main.cpp @@ -1,14 +1,14 @@ -#include "cru/platform/graph/Factory.hpp" -#include "cru/platform/graph/Font.hpp" -#include "cru/platform/graph/Painter.hpp" -#include "cru/platform/native/InputMethod.hpp" -#include "cru/platform/native/UiApplication.hpp" -#include "cru/platform/native/Window.hpp" +#include "cru/platform/graphics/Factory.hpp" +#include "cru/platform/graphics/Font.hpp" +#include "cru/platform/graphics/Painter.hpp" +#include "cru/platform/gui/InputMethod.hpp" +#include "cru/platform/gui/UiApplication.hpp" +#include "cru/platform/gui/Window.hpp" int main() { using namespace cru::platform; - using namespace cru::platform::graph; - using namespace cru::platform::native; + using namespace cru::platform::graphics; + using namespace cru::platform::gui; auto application = CreateUiApplication(); diff --git a/demos/main/main.cpp b/demos/main/main.cpp index e973682e..6bd7fb4e 100644 --- a/demos/main/main.cpp +++ b/demos/main/main.cpp @@ -1,6 +1,6 @@ #include "cru/platform/HeapDebug.hpp" -#include "cru/platform/native/UiApplication.hpp" -#include "cru/platform/native/Window.hpp" +#include "cru/platform/gui/UiApplication.hpp" +#include "cru/platform/gui/Window.hpp" #include "cru/ui/Base.hpp" #include "cru/ui/Window.hpp" #include "cru/ui/WindowHost.hpp" @@ -9,7 +9,7 @@ #include "cru/ui/controls/TextBlock.hpp" #include "cru/ui/controls/TextBox.hpp" -using cru::platform::native::CreateUiApplication; +using cru::platform::gui::CreateUiApplication; using cru::ui::Window; using cru::ui::controls::Button; using cru::ui::controls::FlexLayout; diff --git a/include/cru/platform/graph/Base.hpp b/include/cru/platform/graph/Base.hpp deleted file mode 100644 index 61cfc5ef..00000000 --- a/include/cru/platform/graph/Base.hpp +++ /dev/null @@ -1,24 +0,0 @@ -#pragma once -#include "../GraphBase.hpp" -#include "../Matrix.hpp" -#include "../Resource.hpp" - -#include - -namespace cru::platform::graph { -// forward declarations -struct IGraphFactory; -struct IBrush; -struct ISolidColorBrush; -struct IFont; -struct IGeometry; -struct IGeometryBuilder; -struct IPainter; -struct ITextLayout; - -struct TextHitTestResult { - int position; - bool trailing; - bool insideText; -}; -} // namespace cru::platform::graph diff --git a/include/cru/platform/graph/Brush.hpp b/include/cru/platform/graph/Brush.hpp deleted file mode 100644 index e67384de..00000000 --- a/include/cru/platform/graph/Brush.hpp +++ /dev/null @@ -1,11 +0,0 @@ -#pragma once -#include "Resource.hpp" - -namespace cru::platform::graph { -struct IBrush : virtual IGraphResource {}; - -struct ISolidColorBrush : virtual IBrush { - virtual Color GetColor() = 0; - virtual void SetColor(const Color& color) = 0; -}; -} // namespace cru::platform::graph diff --git a/include/cru/platform/graph/Factory.hpp b/include/cru/platform/graph/Factory.hpp deleted file mode 100644 index b4e68f12..00000000 --- a/include/cru/platform/graph/Factory.hpp +++ /dev/null @@ -1,25 +0,0 @@ -#pragma once -#include "Resource.hpp" - -#include "Brush.hpp" -#include "Font.hpp" -#include "Geometry.hpp" -#include "TextLayout.hpp" - -#include -#include - -namespace cru::platform::graph { -// Entry point of the graph module. -struct IGraphFactory : virtual INativeResource { - virtual std::unique_ptr CreateSolidColorBrush() = 0; - - virtual std::unique_ptr CreateGeometryBuilder() = 0; - - virtual std::unique_ptr CreateFont(std::u16string font_family, - float font_size) = 0; - - virtual std::unique_ptr CreateTextLayout( - std::shared_ptr font, std::u16string text) = 0; -}; -} // namespace cru::platform::graph diff --git a/include/cru/platform/graph/Font.hpp b/include/cru/platform/graph/Font.hpp deleted file mode 100644 index 182cc15b..00000000 --- a/include/cru/platform/graph/Font.hpp +++ /dev/null @@ -1,8 +0,0 @@ -#pragma once -#include "Resource.hpp" - -namespace cru::platform::graph { -struct IFont : virtual IGraphResource { - virtual float GetFontSize() = 0; -}; -} // namespace cru::platform::graph diff --git a/include/cru/platform/graph/Geometry.hpp b/include/cru/platform/graph/Geometry.hpp deleted file mode 100644 index 354efd97..00000000 --- a/include/cru/platform/graph/Geometry.hpp +++ /dev/null @@ -1,20 +0,0 @@ -#pragma once -#include "Resource.hpp" - -namespace cru::platform::graph { -struct IGeometry : virtual IGraphResource { - virtual bool FillContains(const Point& point) = 0; -}; - -// After called Build, calling every method will throw a - -struct IGeometryBuilder : virtual IGraphResource { - virtual void BeginFigure(const Point& point) = 0; - virtual void LineTo(const Point& point) = 0; - virtual void QuadraticBezierTo(const Point& control_point, - const Point& end_point) = 0; - virtual void CloseFigure(bool close) = 0; - - virtual std::unique_ptr Build() = 0; -}; -} // namespace cru::platform::graph diff --git a/include/cru/platform/graph/Painter.hpp b/include/cru/platform/graph/Painter.hpp deleted file mode 100644 index 27ae420b..00000000 --- a/include/cru/platform/graph/Painter.hpp +++ /dev/null @@ -1,29 +0,0 @@ -#pragma once -#include "Resource.hpp" - -namespace cru::platform::graph { - -struct IPainter : virtual INativeResource { - virtual Matrix GetTransform() = 0; - virtual void SetTransform(const Matrix& matrix) = 0; - - virtual void Clear(const Color& color) = 0; - - virtual void StrokeRectangle(const Rect& rectangle, IBrush* brush, - float width) = 0; - virtual void FillRectangle(const Rect& rectangle, IBrush* brush) = 0; - - virtual void StrokeGeometry(IGeometry* geometry, IBrush* brush, - float width) = 0; - virtual void FillGeometry(IGeometry* geometry, IBrush* brush) = 0; - - virtual void DrawText(const Point& offset, ITextLayout* text_layout, - IBrush* brush) = 0; - - virtual void PushLayer(const Rect& bounds) = 0; - - virtual void PopLayer() = 0; - - virtual void EndDraw() = 0; -}; -} // namespace cru::platform::graph diff --git a/include/cru/platform/graph/Resource.hpp b/include/cru/platform/graph/Resource.hpp deleted file mode 100644 index 8859360c..00000000 --- a/include/cru/platform/graph/Resource.hpp +++ /dev/null @@ -1,10 +0,0 @@ -#pragma once -#include "Base.hpp" - -namespace cru::platform::graph { -struct IGraphFactory; - -struct IGraphResource : virtual INativeResource { - virtual IGraphFactory* GetGraphFactory() = 0; -}; -} // namespace cru::platform::graph diff --git a/include/cru/platform/graph/TextLayout.hpp b/include/cru/platform/graph/TextLayout.hpp deleted file mode 100644 index a101983f..00000000 --- a/include/cru/platform/graph/TextLayout.hpp +++ /dev/null @@ -1,24 +0,0 @@ -#pragma once -#include "Resource.hpp" - -#include -#include - -namespace cru::platform::graph { -struct ITextLayout : virtual IGraphResource { - virtual std::u16string GetText() = 0; - virtual std::u16string_view GetTextView() = 0; - virtual void SetText(std::u16string new_text) = 0; - - virtual std::shared_ptr GetFont() = 0; - virtual void SetFont(std::shared_ptr font) = 0; - - virtual void SetMaxWidth(float max_width) = 0; - virtual void SetMaxHeight(float max_height) = 0; - - virtual Rect GetTextBounds() = 0; - virtual std::vector TextRangeRect(const TextRange& text_range) = 0; - virtual Point TextSinglePoint(Index position, bool trailing) = 0; - virtual TextHitTestResult HitTest(const Point& point) = 0; -}; -} // namespace cru::platform::graph diff --git a/include/cru/platform/graph/util/Painter.hpp b/include/cru/platform/graph/util/Painter.hpp deleted file mode 100644 index f9aec027..00000000 --- a/include/cru/platform/graph/util/Painter.hpp +++ /dev/null @@ -1,17 +0,0 @@ -#pragma once -#include "../Painter.hpp" - -#include -#include - -namespace cru::platform::graph::util { -template -void WithTransform(IPainter* painter, const Matrix& matrix, const Fn& action) { - static_assert(std::is_invocable_v, - "Action must can be be invoked with painter."); - const auto old = painter->GetTransform(); - painter->SetTransform(old * matrix); - action(painter); - painter->SetTransform(old); -} -} // namespace cru::platform::graph::util diff --git a/include/cru/platform/graphics/Base.hpp b/include/cru/platform/graphics/Base.hpp new file mode 100644 index 00000000..e751ebdb --- /dev/null +++ b/include/cru/platform/graphics/Base.hpp @@ -0,0 +1,24 @@ +#pragma once +#include "../GraphBase.hpp" +#include "../Matrix.hpp" +#include "../Resource.hpp" + +#include + +namespace cru::platform::graphics { +// forward declarations +struct IGraphFactory; +struct IBrush; +struct ISolidColorBrush; +struct IFont; +struct IGeometry; +struct IGeometryBuilder; +struct IPainter; +struct ITextLayout; + +struct TextHitTestResult { + int position; + bool trailing; + bool insideText; +}; +} // namespace cru::platform::graph diff --git a/include/cru/platform/graphics/Brush.hpp b/include/cru/platform/graphics/Brush.hpp new file mode 100644 index 00000000..10c666b5 --- /dev/null +++ b/include/cru/platform/graphics/Brush.hpp @@ -0,0 +1,11 @@ +#pragma once +#include "Resource.hpp" + +namespace cru::platform::graphics { +struct IBrush : virtual IGraphResource {}; + +struct ISolidColorBrush : virtual IBrush { + virtual Color GetColor() = 0; + virtual void SetColor(const Color& color) = 0; +}; +} // namespace cru::platform::graph diff --git a/include/cru/platform/graphics/Factory.hpp b/include/cru/platform/graphics/Factory.hpp new file mode 100644 index 00000000..d1b37783 --- /dev/null +++ b/include/cru/platform/graphics/Factory.hpp @@ -0,0 +1,25 @@ +#pragma once +#include "Resource.hpp" + +#include "Brush.hpp" +#include "Font.hpp" +#include "Geometry.hpp" +#include "TextLayout.hpp" + +#include +#include + +namespace cru::platform::graphics { +// Entry point of the graph module. +struct IGraphFactory : virtual INativeResource { + virtual std::unique_ptr CreateSolidColorBrush() = 0; + + virtual std::unique_ptr CreateGeometryBuilder() = 0; + + virtual std::unique_ptr CreateFont(std::u16string font_family, + float font_size) = 0; + + virtual std::unique_ptr CreateTextLayout( + std::shared_ptr font, std::u16string text) = 0; +}; +} // namespace cru::platform::graph diff --git a/include/cru/platform/graphics/Font.hpp b/include/cru/platform/graphics/Font.hpp new file mode 100644 index 00000000..70392a69 --- /dev/null +++ b/include/cru/platform/graphics/Font.hpp @@ -0,0 +1,8 @@ +#pragma once +#include "Resource.hpp" + +namespace cru::platform::graphics { +struct IFont : virtual IGraphResource { + virtual float GetFontSize() = 0; +}; +} // namespace cru::platform::graph diff --git a/include/cru/platform/graphics/Geometry.hpp b/include/cru/platform/graphics/Geometry.hpp new file mode 100644 index 00000000..b0ce6ad9 --- /dev/null +++ b/include/cru/platform/graphics/Geometry.hpp @@ -0,0 +1,20 @@ +#pragma once +#include "Resource.hpp" + +namespace cru::platform::graphics { +struct IGeometry : virtual IGraphResource { + virtual bool FillContains(const Point& point) = 0; +}; + +// After called Build, calling every method will throw a + +struct IGeometryBuilder : virtual IGraphResource { + virtual void BeginFigure(const Point& point) = 0; + virtual void LineTo(const Point& point) = 0; + virtual void QuadraticBezierTo(const Point& control_point, + const Point& end_point) = 0; + virtual void CloseFigure(bool close) = 0; + + virtual std::unique_ptr Build() = 0; +}; +} // namespace cru::platform::graph diff --git a/include/cru/platform/graphics/Painter.hpp b/include/cru/platform/graphics/Painter.hpp new file mode 100644 index 00000000..76140c32 --- /dev/null +++ b/include/cru/platform/graphics/Painter.hpp @@ -0,0 +1,29 @@ +#pragma once +#include "Resource.hpp" + +namespace cru::platform::graphics { + +struct IPainter : virtual INativeResource { + virtual Matrix GetTransform() = 0; + virtual void SetTransform(const Matrix& matrix) = 0; + + virtual void Clear(const Color& color) = 0; + + virtual void StrokeRectangle(const Rect& rectangle, IBrush* brush, + float width) = 0; + virtual void FillRectangle(const Rect& rectangle, IBrush* brush) = 0; + + virtual void StrokeGeometry(IGeometry* geometry, IBrush* brush, + float width) = 0; + virtual void FillGeometry(IGeometry* geometry, IBrush* brush) = 0; + + virtual void DrawText(const Point& offset, ITextLayout* text_layout, + IBrush* brush) = 0; + + virtual void PushLayer(const Rect& bounds) = 0; + + virtual void PopLayer() = 0; + + virtual void EndDraw() = 0; +}; +} // namespace cru::platform::graph diff --git a/include/cru/platform/graphics/Resource.hpp b/include/cru/platform/graphics/Resource.hpp new file mode 100644 index 00000000..a1625ce4 --- /dev/null +++ b/include/cru/platform/graphics/Resource.hpp @@ -0,0 +1,10 @@ +#pragma once +#include "Base.hpp" + +namespace cru::platform::graphics { +struct IGraphFactory; + +struct IGraphResource : virtual INativeResource { + virtual IGraphFactory* GetGraphFactory() = 0; +}; +} // namespace cru::platform::graph diff --git a/include/cru/platform/graphics/TextLayout.hpp b/include/cru/platform/graphics/TextLayout.hpp new file mode 100644 index 00000000..efd017d6 --- /dev/null +++ b/include/cru/platform/graphics/TextLayout.hpp @@ -0,0 +1,24 @@ +#pragma once +#include "Resource.hpp" + +#include +#include + +namespace cru::platform::graphics { +struct ITextLayout : virtual IGraphResource { + virtual std::u16string GetText() = 0; + virtual std::u16string_view GetTextView() = 0; + virtual void SetText(std::u16string new_text) = 0; + + virtual std::shared_ptr GetFont() = 0; + virtual void SetFont(std::shared_ptr font) = 0; + + virtual void SetMaxWidth(float max_width) = 0; + virtual void SetMaxHeight(float max_height) = 0; + + virtual Rect GetTextBounds() = 0; + virtual std::vector TextRangeRect(const TextRange& text_range) = 0; + virtual Point TextSinglePoint(Index position, bool trailing) = 0; + virtual TextHitTestResult HitTest(const Point& point) = 0; +}; +} // namespace cru::platform::graph diff --git a/include/cru/platform/graphics/util/Painter.hpp b/include/cru/platform/graphics/util/Painter.hpp new file mode 100644 index 00000000..af3a1997 --- /dev/null +++ b/include/cru/platform/graphics/util/Painter.hpp @@ -0,0 +1,17 @@ +#pragma once +#include "../Painter.hpp" + +#include +#include + +namespace cru::platform::graphics::util { +template +void WithTransform(IPainter* painter, const Matrix& matrix, const Fn& action) { + static_assert(std::is_invocable_v, + "Action must can be be invoked with painter."); + const auto old = painter->GetTransform(); + painter->SetTransform(old * matrix); + action(painter); + painter->SetTransform(old); +} +} // namespace cru::platform::graphics::util diff --git a/include/cru/platform/gui/Base.hpp b/include/cru/platform/gui/Base.hpp new file mode 100644 index 00000000..fb196f02 --- /dev/null +++ b/include/cru/platform/gui/Base.hpp @@ -0,0 +1,47 @@ +#pragma once +#include "Keyboard.hpp" +#include "cru/common/Base.hpp" +#include "cru/common/Bitmask.hpp" +#include "cru/platform/graphics/Base.hpp" + +#include "../Resource.hpp" + +namespace cru::platform::gui { +struct ICursor; +struct ICursorManager; +struct IUiApplication; +struct INativeWindow; +struct IInputMethodContext; + +namespace details { +struct TagMouseButton {}; +} // namespace details + +using MouseButton = Bitmask; + +namespace mouse_buttons { +constexpr MouseButton left{0b1}; +constexpr MouseButton middle{0b10}; +constexpr MouseButton right{0b100}; +} // namespace mouse_buttons + +enum class SystemCursorType { + Arrow, + Hand, +}; + +struct NativeMouseButtonEventArgs { + MouseButton button; + Point point; + KeyModifier modifier; +}; + +struct NativeKeyEventArgs { + KeyCode key; + KeyModifier modifier; +}; + +enum class FocusChangeType { Gain, Lost }; + +enum class MouseEnterLeaveType { Enter, Leave }; +} // namespace cru::platform::gui diff --git a/include/cru/platform/gui/Cursor.hpp b/include/cru/platform/gui/Cursor.hpp new file mode 100644 index 00000000..3f1679e4 --- /dev/null +++ b/include/cru/platform/gui/Cursor.hpp @@ -0,0 +1,14 @@ +#pragma once +#include "Base.hpp" + +#include + +namespace cru::platform::gui { +struct ICursor : virtual INativeResource {}; + +struct ICursorManager : virtual INativeResource { + virtual std::shared_ptr GetSystemCursor(SystemCursorType type) = 0; + + // TODO: Add method to create cursor. +}; +} // namespace cru::platform::gui diff --git a/include/cru/platform/gui/InputMethod.hpp b/include/cru/platform/gui/InputMethod.hpp new file mode 100644 index 00000000..53a8d671 --- /dev/null +++ b/include/cru/platform/gui/InputMethod.hpp @@ -0,0 +1,80 @@ +#pragma once +#include "Base.hpp" + +#include "cru/common/Event.hpp" + +#include +#include +#include + +namespace cru::platform::gui { +struct CompositionClause { + int start; + int end; + bool target; +}; + +using CompositionClauses = std::vector; + +struct CompositionText { + std::u16string text; + CompositionClauses clauses; + TextRange selection; +}; + +struct IInputMethodContext : virtual INativeResource { + // Return true if you should draw composition text manually. Return false if + // system will take care of that for you. + virtual bool ShouldManuallyDrawCompositionText() = 0; + + virtual void EnableIME() = 0; + + virtual void DisableIME() = 0; + + virtual void CompleteComposition() = 0; + + virtual void CancelComposition() = 0; + + virtual CompositionText GetCompositionText() = 0; + + // Set the candidate window lefttop. Use this method to prepare typing. + virtual void SetCandidateWindowPosition(const Point& point) = 0; + + // Triggered when user starts composition. + virtual IEvent* CompositionStartEvent() = 0; + + // Triggered when user stops composition. + virtual IEvent* CompositionEndEvent() = 0; + + // Triggered every time composition text changes. + virtual IEvent* CompositionEvent() = 0; + + virtual IEvent* TextEvent() = 0; +}; +} // namespace cru::platform::gui + +template <> +struct fmt::formatter + : fmt::formatter { + auto parse(fmt::basic_format_parse_context& ctx) { + return fmt::formatter::parse(ctx); + } + + template + auto format(const cru::platform::gui::CompositionText& ct, + FormatContext& ctx) { + auto output = ctx.out(); + output = format_to(output, u"text: {}\n", ct.text); + output = format_to(output, u"clauses:\n"); + for (gsl::index i = 0; i < static_cast(ct.clauses.size()); + i++) { + const auto& clause = ct.clauses[i]; + output = + format_to(output, u"\t{}. start: {} end: {}{}\n", i, clause.start, + clause.end, clause.target ? u" target" : u""); + } + output = format_to(output, u"selection: position: {} count: {}", + ct.selection.position, ct.selection.count); + return output; + } +}; diff --git a/include/cru/platform/gui/Keyboard.hpp b/include/cru/platform/gui/Keyboard.hpp new file mode 100644 index 00000000..e12cccda --- /dev/null +++ b/include/cru/platform/gui/Keyboard.hpp @@ -0,0 +1,127 @@ +#pragma once +#include "cru/common/Bitmask.hpp" + +#include +#include + +namespace cru::platform::gui { +// Because of the complexity of keyboard layout, I only add code in US keyboard +// layout, the most widely used layout in China. We should try to make it easy +// to add new keyboard layout. +enum class KeyCode { + Unknown, + LeftButton, + MiddleButton, + RightButton, + Escape, + F1, + F2, + F3, + F4, + F5, + F6, + F7, + F8, + F9, + F10, + F11, + F12, + N0, + N1, + N2, + N3, + N4, + N5, + N6, + N7, + N8, + N9, + A, + B, + C, + D, + E, + F, + G, + H, + I, + J, + K, + L, + M, + N, + O, + P, + Q, + R, + S, + T, + U, + V, + W, + X, + Y, + Z, + GraveAccent, + Tab, + CapsLock, + LeftShift, + LeftCtrl, + LeftSuper, + LeftAlt, + Minus, + Equal, + Backspace, + LeftSquareBracket, + RightSquareBracket, + BackSlash, + Semicolon, + Quote, + Comma, + Period, + Slash, + RightShift, + RightCtrl, + RightSuper, + RightAlt, + Insert, + Delete, + Home, + End, + PageUp, + PageDown, + Up, + Left, + Down, + Right, + PrintScreen, + ScrollLock, + Pause, + NumPad0, + NumPad1, + NumPad2, + NumPad3, + NumPad4, + NumPad5, + NumPad6, + NumPad7, + NumPad8, + NumPad9 +}; + +namespace details { +struct TagKeyModifier {}; +} // namespace details + +using KeyModifier = Bitmask; + +struct KeyModifiers { + static constexpr KeyModifier shift{0b1}; + static constexpr KeyModifier ctrl{0b10}; + static constexpr KeyModifier alt{0b100}; +}; + +std::u16string_view ToString(KeyCode key_code); +std::u16string ToString(KeyModifier key_modifier, + std::u16string_view separator = u"+"); +} // namespace cru::platform::gui diff --git a/include/cru/platform/gui/UiApplication.hpp b/include/cru/platform/gui/UiApplication.hpp new file mode 100644 index 00000000..6a2eb067 --- /dev/null +++ b/include/cru/platform/gui/UiApplication.hpp @@ -0,0 +1,109 @@ +#pragma once +#include "Base.hpp" + +#include +#include +#include +#include + +namespace cru::platform::gui { +// The entry point of a ui application. +struct IUiApplication : public virtual INativeResource { + public: + static IUiApplication* GetInstance() { return instance; } + + private: + static IUiApplication* instance; + + protected: + IUiApplication(); + + public: + ~IUiApplication() override; + + // Block current thread and run the message loop. Return the exit code when + // message loop gets a quit message (possibly posted by method RequestQuit). + virtual int Run() = 0; + + // Post a quit message with given quit code. + virtual void RequestQuit(int quit_code) = 0; + + virtual void AddOnQuitHandler(std::function handler) = 0; + + // Timer id should always be positive (not 0) and never the same. So it's ok + // to use negative value (or 0) to represent no timer. + virtual long long SetImmediate(std::function action) = 0; + virtual long long SetTimeout(std::chrono::milliseconds milliseconds, + std::function action) = 0; + virtual long long SetInterval(std::chrono::milliseconds milliseconds, + std::function action) = 0; + // Implementation should guarantee calls on timer id already canceled have no + // effects and do not crash. Also canceling negative id or 0 should always + // result in no-op. + virtual void CancelTimer(long long id) = 0; + + virtual std::vector GetAllWindow() = 0; + virtual INativeWindow* CreateWindow(INativeWindow* parent) = 0; + + virtual cru::platform::graphics::IGraphFactory* GetGraphFactory() = 0; + + virtual ICursorManager* GetCursorManager() = 0; +}; + +class TimerAutoCanceler { + public: + TimerAutoCanceler() : id_(0) {} + explicit TimerAutoCanceler(long long id) : id_(id) {} + + CRU_DELETE_COPY(TimerAutoCanceler) + + TimerAutoCanceler(TimerAutoCanceler&& other) : id_(other.id_) { + other.id_ = 0; + } + + TimerAutoCanceler& operator=(TimerAutoCanceler&& other) { + Reset(other.id_); + other.id_ = 0; + return *this; + } + + ~TimerAutoCanceler() { Reset(); } + + long long Release() { + auto temp = id_; + id_ = 0; + return temp; + } + + void Reset(long long id = 0) { + if (id_ > 0) IUiApplication::GetInstance()->CancelTimer(id_); + id_ = id; + } + + private: + long long id_; +}; + +class TimerListAutoCanceler { + public: + TimerListAutoCanceler() = default; + CRU_DELETE_COPY(TimerListAutoCanceler) + CRU_DEFAULT_MOVE(TimerListAutoCanceler) + ~TimerListAutoCanceler() = default; + + TimerListAutoCanceler& operator+=(long long id) { + list_.push_back(TimerAutoCanceler(id)); + return *this; + } + + void Clear() { list_.clear(); } + + bool IsEmpty() const { return list_.empty(); } + + private: + std::vector list_; +}; + +// Bootstrap from this. +std::unique_ptr CreateUiApplication(); +} // namespace cru::platform::gui diff --git a/include/cru/platform/gui/Window.hpp b/include/cru/platform/gui/Window.hpp new file mode 100644 index 00000000..26d1a476 --- /dev/null +++ b/include/cru/platform/gui/Window.hpp @@ -0,0 +1,57 @@ +#pragma once +#include "Base.hpp" + +#include "cru/common/Event.hpp" + +#include + +namespace cru::platform::gui { +// Represents a native window, which exposes some low-level events and +// operations. +struct INativeWindow : virtual INativeResource { + virtual void Close() = 0; + + virtual INativeWindow* GetParent() = 0; + + virtual bool IsVisible() = 0; + virtual void SetVisible(bool is_visible) = 0; + + virtual Size GetClientSize() = 0; + virtual void SetClientSize(const Size& size) = 0; + + // Get the rect of the window containing frame. + // The lefttop of the rect is relative to screen lefttop. + virtual Rect GetWindowRect() = 0; + + // Set the rect of the window containing frame. + // The lefttop of the rect is relative to screen lefttop. + virtual void SetWindowRect(const Rect& rect) = 0; + + // Relative to client lefttop. + virtual Point GetMousePosition() = 0; + + virtual bool CaptureMouse() = 0; + virtual bool ReleaseMouse() = 0; + + virtual void SetCursor(std::shared_ptr cursor) = 0; + + virtual void RequestRepaint() = 0; + + // Remember to call EndDraw on return value and destroy it. + virtual std::unique_ptr BeginPaint() = 0; + + // Don't use this instance after receive this event. + virtual IEvent* DestroyEvent() = 0; + virtual IEvent* PaintEvent() = 0; + virtual IEvent* ResizeEvent() = 0; + virtual IEvent* FocusEvent() = 0; + virtual IEvent* MouseEnterLeaveEvent() = 0; + virtual IEvent* MouseMoveEvent() = 0; + virtual IEvent* MouseDownEvent() = 0; + virtual IEvent* MouseUpEvent() = 0; + virtual IEvent* KeyDownEvent() = 0; + virtual IEvent* KeyUpEvent() = 0; + + virtual IInputMethodContext* GetInputMethodContext() = 0; +}; +} // namespace cru::platform::gui diff --git a/include/cru/platform/native/Base.hpp b/include/cru/platform/native/Base.hpp deleted file mode 100644 index c3e87439..00000000 --- a/include/cru/platform/native/Base.hpp +++ /dev/null @@ -1,47 +0,0 @@ -#pragma once -#include "Keyboard.hpp" -#include "cru/common/Base.hpp" -#include "cru/common/Bitmask.hpp" -#include "cru/platform/graph/Base.hpp" - -#include "../Resource.hpp" - -namespace cru::platform::native { -struct ICursor; -struct ICursorManager; -struct IUiApplication; -struct INativeWindow; -struct IInputMethodContext; - -namespace details { -struct TagMouseButton {}; -} // namespace details - -using MouseButton = Bitmask; - -namespace mouse_buttons { -constexpr MouseButton left{0b1}; -constexpr MouseButton middle{0b10}; -constexpr MouseButton right{0b100}; -} // namespace mouse_buttons - -enum class SystemCursorType { - Arrow, - Hand, -}; - -struct NativeMouseButtonEventArgs { - MouseButton button; - Point point; - KeyModifier modifier; -}; - -struct NativeKeyEventArgs { - KeyCode key; - KeyModifier modifier; -}; - -enum class FocusChangeType { Gain, Lost }; - -enum class MouseEnterLeaveType { Enter, Leave }; -} // namespace cru::platform::native diff --git a/include/cru/platform/native/Cursor.hpp b/include/cru/platform/native/Cursor.hpp deleted file mode 100644 index 447cd694..00000000 --- a/include/cru/platform/native/Cursor.hpp +++ /dev/null @@ -1,14 +0,0 @@ -#pragma once -#include "Base.hpp" - -#include - -namespace cru::platform::native { -struct ICursor : virtual INativeResource {}; - -struct ICursorManager : virtual INativeResource { - virtual std::shared_ptr GetSystemCursor(SystemCursorType type) = 0; - - // TODO: Add method to create cursor. -}; -} // namespace cru::platform::native diff --git a/include/cru/platform/native/InputMethod.hpp b/include/cru/platform/native/InputMethod.hpp deleted file mode 100644 index de752417..00000000 --- a/include/cru/platform/native/InputMethod.hpp +++ /dev/null @@ -1,80 +0,0 @@ -#pragma once -#include "Base.hpp" - -#include "cru/common/Event.hpp" - -#include -#include -#include - -namespace cru::platform::native { -struct CompositionClause { - int start; - int end; - bool target; -}; - -using CompositionClauses = std::vector; - -struct CompositionText { - std::u16string text; - CompositionClauses clauses; - TextRange selection; -}; - -struct IInputMethodContext : virtual INativeResource { - // Return true if you should draw composition text manually. Return false if - // system will take care of that for you. - virtual bool ShouldManuallyDrawCompositionText() = 0; - - virtual void EnableIME() = 0; - - virtual void DisableIME() = 0; - - virtual void CompleteComposition() = 0; - - virtual void CancelComposition() = 0; - - virtual CompositionText GetCompositionText() = 0; - - // Set the candidate window lefttop. Use this method to prepare typing. - virtual void SetCandidateWindowPosition(const Point& point) = 0; - - // Triggered when user starts composition. - virtual IEvent* CompositionStartEvent() = 0; - - // Triggered when user stops composition. - virtual IEvent* CompositionEndEvent() = 0; - - // Triggered every time composition text changes. - virtual IEvent* CompositionEvent() = 0; - - virtual IEvent* TextEvent() = 0; -}; -} // namespace cru::platform::native - -template <> -struct fmt::formatter - : fmt::formatter { - auto parse(fmt::basic_format_parse_context& ctx) { - return fmt::formatter::parse(ctx); - } - - template - auto format(const cru::platform::native::CompositionText& ct, - FormatContext& ctx) { - auto output = ctx.out(); - output = format_to(output, u"text: {}\n", ct.text); - output = format_to(output, u"clauses:\n"); - for (gsl::index i = 0; i < static_cast(ct.clauses.size()); - i++) { - const auto& clause = ct.clauses[i]; - output = - format_to(output, u"\t{}. start: {} end: {}{}\n", i, clause.start, - clause.end, clause.target ? u" target" : u""); - } - output = format_to(output, u"selection: position: {} count: {}", - ct.selection.position, ct.selection.count); - return output; - } -}; diff --git a/include/cru/platform/native/Keyboard.hpp b/include/cru/platform/native/Keyboard.hpp deleted file mode 100644 index 67a35c8a..00000000 --- a/include/cru/platform/native/Keyboard.hpp +++ /dev/null @@ -1,127 +0,0 @@ -#pragma once -#include "cru/common/Bitmask.hpp" - -#include -#include - -namespace cru::platform::native { -// Because of the complexity of keyboard layout, I only add code in US keyboard -// layout, the most widely used layout in China. We should try to make it easy -// to add new keyboard layout. -enum class KeyCode { - Unknown, - LeftButton, - MiddleButton, - RightButton, - Escape, - F1, - F2, - F3, - F4, - F5, - F6, - F7, - F8, - F9, - F10, - F11, - F12, - N0, - N1, - N2, - N3, - N4, - N5, - N6, - N7, - N8, - N9, - A, - B, - C, - D, - E, - F, - G, - H, - I, - J, - K, - L, - M, - N, - O, - P, - Q, - R, - S, - T, - U, - V, - W, - X, - Y, - Z, - GraveAccent, - Tab, - CapsLock, - LeftShift, - LeftCtrl, - LeftSuper, - LeftAlt, - Minus, - Equal, - Backspace, - LeftSquareBracket, - RightSquareBracket, - BackSlash, - Semicolon, - Quote, - Comma, - Period, - Slash, - RightShift, - RightCtrl, - RightSuper, - RightAlt, - Insert, - Delete, - Home, - End, - PageUp, - PageDown, - Up, - Left, - Down, - Right, - PrintScreen, - ScrollLock, - Pause, - NumPad0, - NumPad1, - NumPad2, - NumPad3, - NumPad4, - NumPad5, - NumPad6, - NumPad7, - NumPad8, - NumPad9 -}; - -namespace details { -struct TagKeyModifier {}; -} // namespace details - -using KeyModifier = Bitmask; - -struct KeyModifiers { - static constexpr KeyModifier shift{0b1}; - static constexpr KeyModifier ctrl{0b10}; - static constexpr KeyModifier alt{0b100}; -}; - -std::u16string_view ToString(KeyCode key_code); -std::u16string ToString(KeyModifier key_modifier, - std::u16string_view separator = u"+"); -} // namespace cru::platform::native diff --git a/include/cru/platform/native/UiApplication.hpp b/include/cru/platform/native/UiApplication.hpp deleted file mode 100644 index 2b1b047a..00000000 --- a/include/cru/platform/native/UiApplication.hpp +++ /dev/null @@ -1,109 +0,0 @@ -#pragma once -#include "Base.hpp" - -#include -#include -#include -#include - -namespace cru::platform::native { -// The entry point of a ui application. -struct IUiApplication : public virtual INativeResource { - public: - static IUiApplication* GetInstance() { return instance; } - - private: - static IUiApplication* instance; - - protected: - IUiApplication(); - - public: - ~IUiApplication() override; - - // Block current thread and run the message loop. Return the exit code when - // message loop gets a quit message (possibly posted by method RequestQuit). - virtual int Run() = 0; - - // Post a quit message with given quit code. - virtual void RequestQuit(int quit_code) = 0; - - virtual void AddOnQuitHandler(std::function handler) = 0; - - // Timer id should always be positive (not 0) and never the same. So it's ok - // to use negative value (or 0) to represent no timer. - virtual long long SetImmediate(std::function action) = 0; - virtual long long SetTimeout(std::chrono::milliseconds milliseconds, - std::function action) = 0; - virtual long long SetInterval(std::chrono::milliseconds milliseconds, - std::function action) = 0; - // Implementation should guarantee calls on timer id already canceled have no - // effects and do not crash. Also canceling negative id or 0 should always - // result in no-op. - virtual void CancelTimer(long long id) = 0; - - virtual std::vector GetAllWindow() = 0; - virtual INativeWindow* CreateWindow(INativeWindow* parent) = 0; - - virtual cru::platform::graph::IGraphFactory* GetGraphFactory() = 0; - - virtual ICursorManager* GetCursorManager() = 0; -}; - -class TimerAutoCanceler { - public: - TimerAutoCanceler() : id_(0) {} - explicit TimerAutoCanceler(long long id) : id_(id) {} - - CRU_DELETE_COPY(TimerAutoCanceler) - - TimerAutoCanceler(TimerAutoCanceler&& other) : id_(other.id_) { - other.id_ = 0; - } - - TimerAutoCanceler& operator=(TimerAutoCanceler&& other) { - Reset(other.id_); - other.id_ = 0; - return *this; - } - - ~TimerAutoCanceler() { Reset(); } - - long long Release() { - auto temp = id_; - id_ = 0; - return temp; - } - - void Reset(long long id = 0) { - if (id_ > 0) IUiApplication::GetInstance()->CancelTimer(id_); - id_ = id; - } - - private: - long long id_; -}; - -class TimerListAutoCanceler { - public: - TimerListAutoCanceler() = default; - CRU_DELETE_COPY(TimerListAutoCanceler) - CRU_DEFAULT_MOVE(TimerListAutoCanceler) - ~TimerListAutoCanceler() = default; - - TimerListAutoCanceler& operator+=(long long id) { - list_.push_back(TimerAutoCanceler(id)); - return *this; - } - - void Clear() { list_.clear(); } - - bool IsEmpty() const { return list_.empty(); } - - private: - std::vector list_; -}; - -// Bootstrap from this. -std::unique_ptr CreateUiApplication(); -} // namespace cru::platform::native diff --git a/include/cru/platform/native/Window.hpp b/include/cru/platform/native/Window.hpp deleted file mode 100644 index c8abdeac..00000000 --- a/include/cru/platform/native/Window.hpp +++ /dev/null @@ -1,57 +0,0 @@ -#pragma once -#include "Base.hpp" - -#include "cru/common/Event.hpp" - -#include - -namespace cru::platform::native { -// Represents a native window, which exposes some low-level events and -// operations. -struct INativeWindow : virtual INativeResource { - virtual void Close() = 0; - - virtual INativeWindow* GetParent() = 0; - - virtual bool IsVisible() = 0; - virtual void SetVisible(bool is_visible) = 0; - - virtual Size GetClientSize() = 0; - virtual void SetClientSize(const Size& size) = 0; - - // Get the rect of the window containing frame. - // The lefttop of the rect is relative to screen lefttop. - virtual Rect GetWindowRect() = 0; - - // Set the rect of the window containing frame. - // The lefttop of the rect is relative to screen lefttop. - virtual void SetWindowRect(const Rect& rect) = 0; - - // Relative to client lefttop. - virtual Point GetMousePosition() = 0; - - virtual bool CaptureMouse() = 0; - virtual bool ReleaseMouse() = 0; - - virtual void SetCursor(std::shared_ptr cursor) = 0; - - virtual void RequestRepaint() = 0; - - // Remember to call EndDraw on return value and destroy it. - virtual std::unique_ptr BeginPaint() = 0; - - // Don't use this instance after receive this event. - virtual IEvent* DestroyEvent() = 0; - virtual IEvent* PaintEvent() = 0; - virtual IEvent* ResizeEvent() = 0; - virtual IEvent* FocusEvent() = 0; - virtual IEvent* MouseEnterLeaveEvent() = 0; - virtual IEvent* MouseMoveEvent() = 0; - virtual IEvent* MouseDownEvent() = 0; - virtual IEvent* MouseUpEvent() = 0; - virtual IEvent* KeyDownEvent() = 0; - virtual IEvent* KeyUpEvent() = 0; - - virtual IInputMethodContext* GetInputMethodContext() = 0; -}; -} // namespace cru::platform::native diff --git a/include/cru/ui/Base.hpp b/include/cru/ui/Base.hpp index dd93f187..36d0eb78 100644 --- a/include/cru/ui/Base.hpp +++ b/include/cru/ui/Base.hpp @@ -1,7 +1,7 @@ #pragma once #include "cru/common/Base.hpp" -#include "cru/platform/graph/Base.hpp" -#include "cru/platform/native/Base.hpp" +#include "cru/platform/graphics/Base.hpp" +#include "cru/platform/gui/Base.hpp" #include #include @@ -19,9 +19,9 @@ using cru::platform::RoundedRect; using cru::platform::Size; using cru::platform::TextRange; using cru::platform::Thickness; -using cru::platform::native::MouseButton; +using cru::platform::gui::MouseButton; -namespace mouse_buttons = cru::platform::native::mouse_buttons; +namespace mouse_buttons = cru::platform::gui::mouse_buttons; namespace colors = cru::platform::colors; @@ -83,27 +83,27 @@ inline bool operator!=(const CornerRadius& left, const CornerRadius& right) { } struct BorderStyle { - std::shared_ptr border_brush; + std::shared_ptr border_brush; Thickness border_thickness; CornerRadius border_radius; - std::shared_ptr foreground_brush; - std::shared_ptr background_brush; + std::shared_ptr foreground_brush; + std::shared_ptr background_brush; }; class CanvasPaintEventArgs { public: - CanvasPaintEventArgs(platform::graph::IPainter* painter, + CanvasPaintEventArgs(platform::graphics::IPainter* painter, const Size& paint_size) : painter_(painter), paint_size_(paint_size) {} CRU_DEFAULT_COPY(CanvasPaintEventArgs) CRU_DEFAULT_MOVE(CanvasPaintEventArgs) ~CanvasPaintEventArgs() = default; - platform::graph::IPainter* GetPainter() const { return painter_; } + platform::graphics::IPainter* GetPainter() const { return painter_; } Size GetPaintSize() const { return paint_size_; } private: - platform::graph::IPainter* painter_; + platform::graphics::IPainter* painter_; Size paint_size_; }; diff --git a/include/cru/ui/Control.hpp b/include/cru/ui/Control.hpp index 0021ad62..5f381965 100644 --- a/include/cru/ui/Control.hpp +++ b/include/cru/ui/Control.hpp @@ -58,13 +58,13 @@ class Control : public Object { // Cursor is inherited from parent recursively if not set. public: // null for not set - std::shared_ptr GetCursor(); + std::shared_ptr GetCursor(); // will not return nullptr - std::shared_ptr GetInheritedCursor(); + std::shared_ptr GetInheritedCursor(); // null to unset - void SetCursor(std::shared_ptr cursor); + void SetCursor(std::shared_ptr cursor); //*************** region: events *************** public: @@ -146,6 +146,6 @@ class Control : public Object { private: bool is_mouse_over_ = false; - std::shared_ptr cursor_ = nullptr; + std::shared_ptr cursor_ = nullptr; }; } // namespace cru::ui diff --git a/include/cru/ui/ShortcutHub.hpp b/include/cru/ui/ShortcutHub.hpp index 5382f63e..1145c661 100644 --- a/include/cru/ui/ShortcutHub.hpp +++ b/include/cru/ui/ShortcutHub.hpp @@ -3,7 +3,7 @@ #include "cru/common/Base.hpp" #include "cru/common/Event.hpp" -#include "cru/platform/native/Keyboard.hpp" +#include "cru/platform/gui/Keyboard.hpp" #include "cru/ui/UiEvent.hpp" #include @@ -20,8 +20,8 @@ namespace cru::ui { class ShortcutKeyBind { public: - ShortcutKeyBind(platform::native::KeyCode key, - platform::native::KeyModifier modifier) + ShortcutKeyBind(platform::gui::KeyCode key, + platform::gui::KeyModifier modifier) : key_(key), modifier_(modifier) {} CRU_DEFAULT_COPY(ShortcutKeyBind) @@ -29,11 +29,11 @@ class ShortcutKeyBind { ~ShortcutKeyBind() = default; - platform::native::KeyCode GetKey() const { return key_; } - platform::native::KeyModifier GetModifier() const { return modifier_; } + platform::gui::KeyCode GetKey() const { return key_; } + platform::gui::KeyModifier GetModifier() const { return modifier_; } - bool Is(platform::native::KeyCode key, - platform::native::KeyModifier modifier) const { + bool Is(platform::gui::KeyCode key, + platform::gui::KeyModifier modifier) const { return key == key_ && modifier == modifier_; } @@ -47,15 +47,15 @@ class ShortcutKeyBind { std::u16string ToString() { std::u16string result = u"("; - result += platform::native::ToString(modifier_); + result += platform::gui::ToString(modifier_); result += u")"; - result += platform::native::ToString(key_); + result += platform::gui::ToString(key_); return result; } private: - platform::native::KeyCode key_; - platform::native::KeyModifier modifier_; + platform::gui::KeyCode key_; + platform::gui::KeyModifier modifier_; }; } // namespace cru::ui diff --git a/include/cru/ui/UiEvent.hpp b/include/cru/ui/UiEvent.hpp index 5adace8a..c0b2a902 100644 --- a/include/cru/ui/UiEvent.hpp +++ b/include/cru/ui/UiEvent.hpp @@ -2,14 +2,14 @@ #include "Base.hpp" #include "cru/common/Event.hpp" -#include "cru/platform/native/Keyboard.hpp" +#include "cru/platform/gui/Keyboard.hpp" #include #include #include #include -namespace cru::platform::graph { +namespace cru::platform::graphics { struct IPainter; } @@ -94,13 +94,13 @@ class MouseButtonEventArgs : public MouseEventArgs { public: MouseButtonEventArgs(Object* sender, Object* original_sender, const Point& point, const MouseButton button, - platform::native::KeyModifier key_modifier) + platform::gui::KeyModifier key_modifier) : MouseEventArgs(sender, original_sender, point), button_(button), key_modifier_(key_modifier) {} MouseButtonEventArgs(Object* sender, Object* original_sender, const MouseButton button, - platform::native::KeyModifier key_modifier) + platform::gui::KeyModifier key_modifier) : MouseEventArgs(sender, original_sender), button_(button), key_modifier_(key_modifier) {} @@ -111,11 +111,11 @@ class MouseButtonEventArgs : public MouseEventArgs { ~MouseButtonEventArgs() override = default; MouseButton GetButton() const { return button_; } - platform::native::KeyModifier GetKeyModifier() const { return key_modifier_; } + platform::gui::KeyModifier GetKeyModifier() const { return key_modifier_; } private: MouseButton button_; - platform::native::KeyModifier key_modifier_; + platform::gui::KeyModifier key_modifier_; }; class MouseWheelEventArgs : public MouseEventArgs { @@ -138,7 +138,7 @@ class MouseWheelEventArgs : public MouseEventArgs { class PaintEventArgs : public UiEventArgs { public: PaintEventArgs(Object* sender, Object* original_sender, - platform::graph::IPainter* painter) + platform::graphics::IPainter* painter) : UiEventArgs(sender, original_sender), painter_(painter) {} PaintEventArgs(const PaintEventArgs& other) = default; PaintEventArgs(PaintEventArgs&& other) = default; @@ -146,10 +146,10 @@ class PaintEventArgs : public UiEventArgs { PaintEventArgs& operator=(PaintEventArgs&& other) = default; ~PaintEventArgs() = default; - platform::graph::IPainter* GetPainter() const { return painter_; } + platform::graphics::IPainter* GetPainter() const { return painter_; } private: - platform::graph::IPainter* painter_; + platform::graphics::IPainter* painter_; }; class FocusChangeEventArgs : public UiEventArgs { @@ -191,8 +191,8 @@ class ToggleEventArgs : public UiEventArgs { class KeyEventArgs : public UiEventArgs { public: KeyEventArgs(Object* sender, Object* original_sender, - platform::native::KeyCode key_code, - platform::native::KeyModifier key_modifier) + platform::gui::KeyCode key_code, + platform::gui::KeyModifier key_modifier) : UiEventArgs(sender, original_sender), key_code_(key_code), key_modifier_(key_modifier) {} @@ -202,12 +202,12 @@ class KeyEventArgs : public UiEventArgs { KeyEventArgs& operator=(KeyEventArgs&& other) = default; ~KeyEventArgs() override = default; - platform::native::KeyCode GetKeyCode() const { return key_code_; } - platform::native::KeyModifier GetKeyModifier() const { return key_modifier_; } + platform::gui::KeyCode GetKeyCode() const { return key_code_; } + platform::gui::KeyModifier GetKeyModifier() const { return key_modifier_; } private: - platform::native::KeyCode key_code_; - platform::native::KeyModifier key_modifier_; + platform::gui::KeyCode key_code_; + platform::gui::KeyModifier key_modifier_; }; class CharEventArgs : public UiEventArgs { diff --git a/include/cru/ui/UiManager.hpp b/include/cru/ui/UiManager.hpp index 46f06ac2..64599d99 100644 --- a/include/cru/ui/UiManager.hpp +++ b/include/cru/ui/UiManager.hpp @@ -9,10 +9,10 @@ namespace cru::ui { struct ThemeResources { std::u16string default_font_family; - std::shared_ptr default_font; - std::shared_ptr text_brush; - std::shared_ptr text_selection_brush; - std::shared_ptr caret_brush; + std::shared_ptr default_font; + std::shared_ptr text_brush; + std::shared_ptr text_selection_brush; + std::shared_ptr caret_brush; controls::ButtonStyle button_style; controls::TextBoxBorderStyle text_box_border_style; }; diff --git a/include/cru/ui/WindowHost.hpp b/include/cru/ui/WindowHost.hpp index c3221dcf..97acf72e 100644 --- a/include/cru/ui/WindowHost.hpp +++ b/include/cru/ui/WindowHost.hpp @@ -2,8 +2,8 @@ #include "Base.hpp" #include "cru/common/Event.hpp" -#include "cru/platform/native/UiApplication.hpp" -#include "cru/platform/native/Window.hpp" +#include "cru/platform/gui/UiApplication.hpp" +#include "cru/platform/gui/Window.hpp" #include "render/Base.hpp" #include @@ -24,7 +24,7 @@ class WindowHost : public Object { ~WindowHost() override; public: - platform::native::INativeWindow* GetNativeWindow() { return native_window_; } + platform::gui::INativeWindow* GetNativeWindow() { return native_window_; } // Mark the layout as invalid, and arrange a re-layout later. // This method could be called more than one times in a message cycle. But @@ -87,30 +87,30 @@ class WindowHost : public Object { private: //*************** region: native messages *************** - void OnNativeDestroy(platform::native::INativeWindow* window, std::nullptr_t); - void OnNativePaint(platform::native::INativeWindow* window, std::nullptr_t); - void OnNativeResize(platform::native::INativeWindow* window, + void OnNativeDestroy(platform::gui::INativeWindow* window, std::nullptr_t); + void OnNativePaint(platform::gui::INativeWindow* window, std::nullptr_t); + void OnNativeResize(platform::gui::INativeWindow* window, const Size& size); - void OnNativeFocus(platform::native::INativeWindow* window, - cru::platform::native::FocusChangeType focus); + void OnNativeFocus(platform::gui::INativeWindow* window, + cru::platform::gui::FocusChangeType focus); void OnNativeMouseEnterLeave( - platform::native::INativeWindow* window, - cru::platform::native::MouseEnterLeaveType enter); - void OnNativeMouseMove(platform::native::INativeWindow* window, + platform::gui::INativeWindow* window, + cru::platform::gui::MouseEnterLeaveType enter); + void OnNativeMouseMove(platform::gui::INativeWindow* window, const Point& point); void OnNativeMouseDown( - platform::native::INativeWindow* window, - const platform::native::NativeMouseButtonEventArgs& args); + platform::gui::INativeWindow* window, + const platform::gui::NativeMouseButtonEventArgs& args); void OnNativeMouseUp( - platform::native::INativeWindow* window, - const platform::native::NativeMouseButtonEventArgs& args); + platform::gui::INativeWindow* window, + const platform::gui::NativeMouseButtonEventArgs& args); - void OnNativeKeyDown(platform::native::INativeWindow* window, - const platform::native::NativeKeyEventArgs& args); - void OnNativeKeyUp(platform::native::INativeWindow* window, - const platform::native::NativeKeyEventArgs& args); + void OnNativeKeyDown(platform::gui::INativeWindow* window, + const platform::gui::NativeKeyEventArgs& args); + void OnNativeKeyUp(platform::gui::INativeWindow* window, + const platform::gui::NativeKeyEventArgs& args); //*************** region: event dispatcher helper *************** @@ -123,10 +123,10 @@ class WindowHost : public Object { Control* root_control_ = nullptr; render::RenderObject* root_render_object_ = nullptr; - platform::native::INativeWindow* native_window_ = nullptr; + platform::gui::INativeWindow* native_window_ = nullptr; bool need_layout_ = false; - platform::native::TimerAutoCanceler relayout_timer_canceler_; + platform::gui::TimerAutoCanceler relayout_timer_canceler_; Event after_layout_event_; std::vector > after_layout_stable_action_; diff --git a/include/cru/ui/render/BorderRenderObject.hpp b/include/cru/ui/render/BorderRenderObject.hpp index 587f051a..f1b957cf 100644 --- a/include/cru/ui/render/BorderRenderObject.hpp +++ b/include/cru/ui/render/BorderRenderObject.hpp @@ -16,11 +16,11 @@ class BorderRenderObject : public RenderObject { bool IsBorderEnabled() const { return is_border_enabled_; } void SetBorderEnabled(bool enabled) { is_border_enabled_ = enabled; } - std::shared_ptr GetBorderBrush() { + std::shared_ptr GetBorderBrush() { return border_brush_; } - void SetBorderBrush(std::shared_ptr brush) { + void SetBorderBrush(std::shared_ptr brush) { if (brush == border_brush_) return; border_brush_ = std::move(brush); InvalidatePaint(); @@ -42,21 +42,21 @@ class BorderRenderObject : public RenderObject { RecreateGeometry(); } - std::shared_ptr GetForegroundBrush() { + std::shared_ptr GetForegroundBrush() { return foreground_brush_; } - void SetForegroundBrush(std::shared_ptr brush) { + void SetForegroundBrush(std::shared_ptr brush) { if (brush == foreground_brush_) return; foreground_brush_ = std::move(brush); InvalidatePaint(); } - std::shared_ptr GetBackgroundBrush() { + std::shared_ptr GetBackgroundBrush() { return background_brush_; } - void SetBackgroundBrush(std::shared_ptr brush) { + void SetBackgroundBrush(std::shared_ptr brush) { if (brush == background_brush_) return; background_brush_ = std::move(brush); InvalidatePaint(); @@ -67,7 +67,7 @@ class BorderRenderObject : public RenderObject { RenderObject* HitTest(const Point& point) override; protected: - void OnDrawCore(platform::graph::IPainter* painter) override; + void OnDrawCore(platform::graphics::IPainter* painter) override; Size OnMeasureCore(const MeasureRequirement& requirement, const MeasureSize& preferred_size) override; @@ -87,19 +87,19 @@ class BorderRenderObject : public RenderObject { private: bool is_border_enabled_ = false; - std::shared_ptr border_brush_; + std::shared_ptr border_brush_; Thickness border_thickness_; CornerRadius border_radius_; - std::shared_ptr foreground_brush_; - std::shared_ptr background_brush_; + std::shared_ptr foreground_brush_; + std::shared_ptr background_brush_; // The ring. Used for painting. - std::unique_ptr geometry_; + std::unique_ptr geometry_; // Area including inner area of the border. Used for painting foreground and // background. - std::unique_ptr border_inner_geometry_; + std::unique_ptr border_inner_geometry_; // Area including border ring and inner area. Used for hit test. - std::unique_ptr border_outer_geometry_; + std::unique_ptr border_outer_geometry_; }; } // namespace cru::ui::render diff --git a/include/cru/ui/render/CanvasRenderObject.hpp b/include/cru/ui/render/CanvasRenderObject.hpp index 3216f08c..58fee59c 100644 --- a/include/cru/ui/render/CanvasRenderObject.hpp +++ b/include/cru/ui/render/CanvasRenderObject.hpp @@ -22,7 +22,7 @@ class CanvasRenderObject : public RenderObject { IEvent* PaintEvent() { return &paint_event_; } protected: - void OnDrawContent(platform::graph::IPainter* painter) override; + void OnDrawContent(platform::graphics::IPainter* painter) override; Size OnMeasureContent(const MeasureRequirement& requirement, const MeasureSize& preferred_size) override; diff --git a/include/cru/ui/render/LayoutRenderObject.hpp b/include/cru/ui/render/LayoutRenderObject.hpp index b46ba0d0..732031a1 100644 --- a/include/cru/ui/render/LayoutRenderObject.hpp +++ b/include/cru/ui/render/LayoutRenderObject.hpp @@ -1,7 +1,7 @@ #pragma once #include "RenderObject.hpp" -#include "cru/platform/graph/util/Painter.hpp" +#include "cru/platform/graphics/util/Painter.hpp" namespace cru::ui::render { template diff --git a/include/cru/ui/render/RenderObject.hpp b/include/cru/ui/render/RenderObject.hpp index 20e095fa..436cf6b2 100644 --- a/include/cru/ui/render/RenderObject.hpp +++ b/include/cru/ui/render/RenderObject.hpp @@ -33,7 +33,7 @@ namespace cru::ui::render { // // To write a custom RenderObject, override following methods: // public: -// void Draw(platform::graph::IPainter* painter) override; +// void Draw(platform::graphics::IPainter* painter) override; // RenderObject* HitTest(const Point& point) override; // protected: // Size OnMeasureContent(const MeasureRequirement& requirement) override; @@ -129,7 +129,7 @@ class RenderObject : public Object { // This will set offset of this render object and call OnLayoutCore. void Layout(const Point& offset); - void Draw(platform::graph::IPainter* painter); + void Draw(platform::graphics::IPainter* painter); // Param point must be relative the lefttop of render object including margin. // Add offset before pass point to children. @@ -163,15 +163,15 @@ class RenderObject : public Object { virtual void OnRemoveChild(RenderObject* removed_child, Index position); // Draw all children with offset. - void DefaultDrawChildren(platform::graph::IPainter* painter); + void DefaultDrawChildren(platform::graphics::IPainter* painter); // Draw all children with translation of content rect lefttop. - void DefaultDrawContent(platform::graph::IPainter* painter); + void DefaultDrawContent(platform::graphics::IPainter* painter); // Call DefaultDrawContent. Then call DefaultDrawChildren. - virtual void OnDrawCore(platform::graph::IPainter* painter); + virtual void OnDrawCore(platform::graphics::IPainter* painter); - virtual void OnDrawContent(platform::graph::IPainter* painter); + virtual void OnDrawContent(platform::graphics::IPainter* painter); // Size measure including margin and padding. Please reduce margin and padding // or other custom things and pass the result content measure requirement and diff --git a/include/cru/ui/render/ScrollRenderObject.hpp b/include/cru/ui/render/ScrollRenderObject.hpp index 9b0cbf9a..3cc0e4c4 100644 --- a/include/cru/ui/render/ScrollRenderObject.hpp +++ b/include/cru/ui/render/ScrollRenderObject.hpp @@ -1,7 +1,7 @@ #pragma once #include "RenderObject.hpp" -#include "cru/platform/graph/util/Painter.hpp" +#include "cru/platform/graphics/util/Painter.hpp" #include @@ -44,7 +44,7 @@ class ScrollRenderObject : public RenderObject { void ScrollToContain(const Rect& rect, const Thickness& margin = Thickness{}); protected: - void OnDrawCore(platform::graph::IPainter* painter) override; + void OnDrawCore(platform::graphics::IPainter* painter) override; // Logic: // If available size is bigger than child's preferred size, then child's diff --git a/include/cru/ui/render/TextRenderObject.hpp b/include/cru/ui/render/TextRenderObject.hpp index 3be42bbb..fa569c8c 100644 --- a/include/cru/ui/render/TextRenderObject.hpp +++ b/include/cru/ui/render/TextRenderObject.hpp @@ -24,10 +24,10 @@ class TextRenderObject : public RenderObject { constexpr static float default_caret_width = 2; public: - TextRenderObject(std::shared_ptr brush, - std::shared_ptr font, - std::shared_ptr selection_brush, - std::shared_ptr caret_brush); + TextRenderObject(std::shared_ptr brush, + std::shared_ptr font, + std::shared_ptr selection_brush, + std::shared_ptr caret_brush); TextRenderObject(const TextRenderObject& other) = delete; TextRenderObject(TextRenderObject&& other) = delete; TextRenderObject& operator=(const TextRenderObject& other) = delete; @@ -38,25 +38,25 @@ class TextRenderObject : public RenderObject { std::u16string_view GetTextView() const; void SetText(std::u16string new_text); - std::shared_ptr GetBrush() const { return brush_; } - void SetBrush(std::shared_ptr new_brush); + std::shared_ptr GetBrush() const { return brush_; } + void SetBrush(std::shared_ptr new_brush); - std::shared_ptr GetFont() const; - void SetFont(std::shared_ptr font); + std::shared_ptr GetFont() const; + void SetFont(std::shared_ptr font); std::vector TextRangeRect(const TextRange& text_range); Point TextSinglePoint(gsl::index position, bool trailing); - platform::graph::TextHitTestResult TextHitTest(const Point& point); + platform::graphics::TextHitTestResult TextHitTest(const Point& point); std::optional GetSelectionRange() const { return selection_range_; } void SetSelectionRange(std::optional new_range); - std::shared_ptr GetSelectionBrush() const { + std::shared_ptr GetSelectionBrush() const { return selection_brush_; } - void SetSelectionBrush(std::shared_ptr new_brush); + void SetSelectionBrush(std::shared_ptr new_brush); bool IsDrawCaret() const { return draw_caret_; } void SetDrawCaret(bool draw_caret); @@ -72,10 +72,10 @@ class TextRenderObject : public RenderObject { // Lefttop relative to render object lefttop. Rect GetCaretRect(); - std::shared_ptr GetCaretBrush() const { + std::shared_ptr GetCaretBrush() const { return caret_brush_; } - void GetCaretBrush(std::shared_ptr brush); + void GetCaretBrush(std::shared_ptr brush); float GetCaretWidth() const { return caret_width_; } void SetCaretWidth(float width); @@ -83,7 +83,7 @@ class TextRenderObject : public RenderObject { RenderObject* HitTest(const Point& point) override; protected: - void OnDrawContent(platform::graph::IPainter* painter) override; + void OnDrawContent(platform::graphics::IPainter* painter) override; // See remarks of this class. Size OnMeasureContent(const MeasureRequirement& requirement, @@ -93,16 +93,16 @@ class TextRenderObject : public RenderObject { void OnAfterLayout() override; private: - std::shared_ptr brush_; - std::shared_ptr font_; - std::unique_ptr text_layout_; + std::shared_ptr brush_; + std::shared_ptr font_; + std::unique_ptr text_layout_; std::optional selection_range_ = std::nullopt; - std::shared_ptr selection_brush_; + std::shared_ptr selection_brush_; bool draw_caret_ = false; gsl::index caret_position_ = 0; - std::shared_ptr caret_brush_; + std::shared_ptr caret_brush_; float caret_width_ = default_caret_width; }; } // namespace cru::ui::render diff --git a/include/cru/win/graph/direct/Brush.hpp b/include/cru/win/graph/direct/Brush.hpp deleted file mode 100644 index df1debe3..00000000 --- a/include/cru/win/graph/direct/Brush.hpp +++ /dev/null @@ -1,39 +0,0 @@ -#pragma once -#include "ComResource.hpp" -#include "Resource.hpp" - -#include "cru/platform/graph/Brush.hpp" - -namespace cru::platform::graph::win::direct { -struct ID2DBrush : virtual IBrush { - virtual ID2D1Brush* GetD2DBrushInterface() const = 0; -}; - -class D2DSolidColorBrush : public DirectGraphResource, - public virtual ISolidColorBrush, - public virtual ID2DBrush, - public virtual IComResource { - public: - explicit D2DSolidColorBrush(DirectGraphFactory* factory); - - CRU_DELETE_COPY(D2DSolidColorBrush) - CRU_DELETE_MOVE(D2DSolidColorBrush) - - ~D2DSolidColorBrush() override = default; - - public: - Color GetColor() override { return color_; } - void SetColor(const Color& color) override; - - ID2D1Brush* GetD2DBrushInterface() const override { return brush_.Get(); } - - ID2D1SolidColorBrush* GetComInterface() const override { - return brush_.Get(); - } - - private: - Color color_ = colors::black; - - Microsoft::WRL::ComPtr brush_; -}; -} // namespace cru::platform::graph::win::direct diff --git a/include/cru/win/graph/direct/ComResource.hpp b/include/cru/win/graph/direct/ComResource.hpp deleted file mode 100644 index 2ac332cd..00000000 --- a/include/cru/win/graph/direct/ComResource.hpp +++ /dev/null @@ -1,11 +0,0 @@ -#pragma once -#include "../../WinPreConfig.hpp" - -#include "cru/common/Base.hpp" - -namespace cru::platform::graph::win::direct { -template -struct IComResource : virtual Interface { - virtual TInterface* GetComInterface() const = 0; -}; -} // namespace cru::platform::graph::win::direct diff --git a/include/cru/win/graph/direct/ConvertUtil.hpp b/include/cru/win/graph/direct/ConvertUtil.hpp deleted file mode 100644 index 12a04c7b..00000000 --- a/include/cru/win/graph/direct/ConvertUtil.hpp +++ /dev/null @@ -1,107 +0,0 @@ -#pragma once -#include "../../WinPreConfig.hpp" - -#include "cru/platform/graph/Base.hpp" - -namespace cru::platform::graph::win::direct { -inline D2D1_MATRIX_3X2_F Convert(const platform::Matrix& matrix) { - D2D1_MATRIX_3X2_F m; - m._11 = matrix.m11; - m._12 = matrix.m12; - m._21 = matrix.m21; - m._22 = matrix.m22; - m._31 = matrix.m31; - m._32 = matrix.m32; - return m; -} - -inline D2D1_COLOR_F Convert(const Color& color) { - return D2D1::ColorF(color.red / 255.0f, color.green / 255.0f, - color.blue / 255.0f, color.alpha / 255.0f); -} - -inline D2D1_POINT_2F Convert(const Point& point) { - return D2D1::Point2F(point.x, point.y); -} - -inline D2D1_RECT_F Convert(const Rect& rect) { - return D2D1::RectF(rect.left, rect.top, rect.left + rect.width, - rect.top + rect.height); -} - -inline D2D1_ROUNDED_RECT Convert(const RoundedRect& rounded_rect) { - return D2D1::RoundedRect(Convert(rounded_rect.rect), rounded_rect.radius_x, - rounded_rect.radius_y); -} - -inline D2D1_ELLIPSE Convert(const Ellipse& ellipse) { - return D2D1::Ellipse(Convert(ellipse.center), ellipse.radius_x, - ellipse.radius_y); -} - -inline platform::Matrix Convert(const D2D1_MATRIX_3X2_F& matrix) { - return platform::Matrix{matrix._11, matrix._12, matrix._21, - matrix._22, matrix._31, matrix._32}; -} - -inline Color Convert(const D2D1_COLOR_F& color) { - auto floor = [](float n) { return static_cast(n + 0.5f); }; - return Color{floor(color.r * 255.0f), floor(color.g * 255.0f), - floor(color.b * 255.0f), floor(color.a * 255.0f)}; -} - -inline Point Convert(const D2D1_POINT_2F& point) { - return Point(point.x, point.y); -} - -inline Rect Convert(const D2D1_RECT_F& rect) { - return Rect(rect.left, rect.top, rect.right - rect.left, - rect.bottom - rect.top); -} - -inline RoundedRect Convert(const D2D1_ROUNDED_RECT& rounded_rect) { - return RoundedRect(Convert(rounded_rect.rect), rounded_rect.radiusX, - rounded_rect.radiusY); -} - -inline Ellipse Convert(const D2D1_ELLIPSE& ellipse) { - return Ellipse(Convert(ellipse.point), ellipse.radiusX, ellipse.radiusY); -} - -inline bool operator==(const D2D1_POINT_2F& left, const D2D1_POINT_2F& right) { - return left.x == right.x && left.y == right.y; -} - -inline bool operator!=(const D2D1_POINT_2F& left, const D2D1_POINT_2F& right) { - return !(left == right); -} - -inline bool operator==(const D2D1_RECT_F& left, const D2D1_RECT_F& right) { - return left.left == right.left && left.top == right.top && - left.right == right.right && left.bottom == right.bottom; -} - -inline bool operator!=(const D2D1_RECT_F& left, const D2D1_RECT_F& right) { - return !(left == right); -} - -inline bool operator==(const D2D1_ROUNDED_RECT& left, - const D2D1_ROUNDED_RECT& right) { - return left.rect == right.rect && left.radiusX == right.radiusX && - left.radiusY == right.radiusY; -} - -inline bool operator!=(const D2D1_ROUNDED_RECT& left, - const D2D1_ROUNDED_RECT& right) { - return !(left == right); -} - -inline bool operator==(const D2D1_ELLIPSE& left, const D2D1_ELLIPSE& right) { - return left.point == right.point && left.radiusX == right.radiusX && - left.radiusY == right.radiusY; -} - -inline bool operator!=(const D2D1_ELLIPSE& left, const D2D1_ELLIPSE& right) { - return !(left == right); -} -} // namespace cru::platform::graph::win::direct diff --git a/include/cru/win/graph/direct/Exception.hpp b/include/cru/win/graph/direct/Exception.hpp deleted file mode 100644 index 8b62e8fa..00000000 --- a/include/cru/win/graph/direct/Exception.hpp +++ /dev/null @@ -1,7 +0,0 @@ -#pragma once -#include "../../Exception.hpp" - -namespace cru::platform::graph::win::direct { -using platform::win::HResultError; -using platform::win::ThrowIfFailed; -} // namespace cru::platform::graph::win::direct \ No newline at end of file diff --git a/include/cru/win/graph/direct/Factory.hpp b/include/cru/win/graph/direct/Factory.hpp deleted file mode 100644 index e70454f5..00000000 --- a/include/cru/win/graph/direct/Factory.hpp +++ /dev/null @@ -1,58 +0,0 @@ -#pragma once -#include "Resource.hpp" - -#include "cru/platform/graph/Factory.hpp" - -namespace cru::platform::graph::win::direct { -class DirectGraphFactory : public DirectResource, public virtual IGraphFactory { - public: - DirectGraphFactory(); - - CRU_DELETE_COPY(DirectGraphFactory) - CRU_DELETE_MOVE(DirectGraphFactory) - - ~DirectGraphFactory() override; - - public: - ID3D11Device* GetD3D11Device() const { return d3d11_device_.Get(); } - ID2D1Factory1* GetD2D1Factory() const { return d2d1_factory_.Get(); } - ID2D1Device* GetD2D1Device() const { return d2d1_device_.Get(); } - IDXGIFactory2* GetDxgiFactory() const { return dxgi_factory_.Get(); } - IDWriteFactory* GetDWriteFactory() const { return dwrite_factory_.Get(); } - IDWriteFontCollection* GetSystemFontCollection() const { - return dwrite_system_font_collection_.Get(); - } - - public: - Microsoft::WRL::ComPtr CreateD2D1DeviceContext(); - - // This context should only be used to create graphic resources like brush. - // Because graphic resources can be shared if they are created in the same - // device. - ID2D1DeviceContext* GetDefaultD2D1DeviceContext() { - return d2d1_device_context_.Get(); - } - - public: - std::unique_ptr CreateSolidColorBrush() override; - - std::unique_ptr CreateGeometryBuilder() override; - - std::unique_ptr CreateFont(std::u16string font_family, - float font_size) override; - - std::unique_ptr CreateTextLayout(std::shared_ptr font, - std::u16string text) override; - - private: - Microsoft::WRL::ComPtr d3d11_device_; - // ID2D1Factory1 is a interface only available in Windows 8 and Windows 7 with - // update. It is d2d v1.1. - Microsoft::WRL::ComPtr d2d1_factory_; - Microsoft::WRL::ComPtr d2d1_device_; - Microsoft::WRL::ComPtr d2d1_device_context_; - Microsoft::WRL::ComPtr dxgi_factory_; - Microsoft::WRL::ComPtr dwrite_factory_; - Microsoft::WRL::ComPtr dwrite_system_font_collection_; -}; -} // namespace cru::platform::graph::win::direct diff --git a/include/cru/win/graph/direct/Font.hpp b/include/cru/win/graph/direct/Font.hpp deleted file mode 100644 index 2195f3e4..00000000 --- a/include/cru/win/graph/direct/Font.hpp +++ /dev/null @@ -1,33 +0,0 @@ -#pragma once -#include "ComResource.hpp" -#include "Resource.hpp" - -#include "cru/platform/graph/Font.hpp" - -#include - -namespace cru::platform::graph::win::direct { -class DWriteFont : public DirectGraphResource, - public virtual IFont, - public virtual IComResource { - public: - DWriteFont(DirectGraphFactory* factory, std::u16string font_family, - float font_size); - - CRU_DELETE_COPY(DWriteFont) - CRU_DELETE_MOVE(DWriteFont) - - ~DWriteFont() override = default; - - public: - IDWriteTextFormat* GetComInterface() const override { - return text_format_.Get(); - } - - float GetFontSize() override; - - private: - std::u16string font_family_; - Microsoft::WRL::ComPtr text_format_; -}; -} // namespace cru::platform::graph::win::direct diff --git a/include/cru/win/graph/direct/Geometry.hpp b/include/cru/win/graph/direct/Geometry.hpp deleted file mode 100644 index 87987d3e..00000000 --- a/include/cru/win/graph/direct/Geometry.hpp +++ /dev/null @@ -1,57 +0,0 @@ -#pragma once -#include "ComResource.hpp" -#include "Resource.hpp" - -#include "cru/platform/graph/Geometry.hpp" - -namespace cru::platform::graph::win::direct { -class D2DGeometryBuilder : public DirectGraphResource, - public virtual IGeometryBuilder { - public: - explicit D2DGeometryBuilder(DirectGraphFactory* factory); - - CRU_DELETE_COPY(D2DGeometryBuilder) - CRU_DELETE_MOVE(D2DGeometryBuilder) - - ~D2DGeometryBuilder() override = default; - - public: - void BeginFigure(const Point& point) override; - void LineTo(const Point& point) override; - void QuadraticBezierTo(const Point& control_point, - const Point& end_point) override; - void CloseFigure(bool close) override; - - std::unique_ptr Build() override; - - private: - bool IsValid() { return geometry_ != nullptr; } - void CheckValidation(); - - private: - Microsoft::WRL::ComPtr geometry_; - Microsoft::WRL::ComPtr geometry_sink_; -}; - -class D2DGeometry : public DirectGraphResource, - public virtual IGeometry, - public IComResource { - public: - D2DGeometry(DirectGraphFactory* factory, - Microsoft::WRL::ComPtr geometry); - - CRU_DELETE_COPY(D2DGeometry) - CRU_DELETE_MOVE(D2DGeometry) - - ~D2DGeometry() override = default; - - public: - ID2D1Geometry* GetComInterface() const override { return geometry_.Get(); } - - public: - bool FillContains(const Point& point) override; - - private: - Microsoft::WRL::ComPtr geometry_; -}; -} // namespace cru::platform::graph::win::direct diff --git a/include/cru/win/graph/direct/Painter.hpp b/include/cru/win/graph/direct/Painter.hpp deleted file mode 100644 index a50f962d..00000000 --- a/include/cru/win/graph/direct/Painter.hpp +++ /dev/null @@ -1,60 +0,0 @@ -#pragma once -#include "ComResource.hpp" -#include "Resource.hpp" - -#include "cru/platform/graph/Painter.hpp" - -#include - -namespace cru::platform::graph::win::direct { -class D2DPainter : public DirectResource, - public virtual IPainter, - public virtual IComResource { - public: - explicit D2DPainter(ID2D1RenderTarget* render_target); - - CRU_DELETE_COPY(D2DPainter) - CRU_DELETE_MOVE(D2DPainter) - - ~D2DPainter() override = default; - - public: - ID2D1RenderTarget* GetComInterface() const override { return render_target_; } - - public: - Matrix GetTransform() override; - void SetTransform(const platform::Matrix& matrix) override; - - void Clear(const Color& color) override; - - void StrokeRectangle(const Rect& rectangle, IBrush* brush, - float width) override; - void FillRectangle(const Rect& rectangle, IBrush* brush) override; - - void StrokeGeometry(IGeometry* geometry, IBrush* brush, float width) override; - void FillGeometry(IGeometry* geometry, IBrush* brush) override; - - void DrawText(const Point& offset, ITextLayout* text_layout, - IBrush* brush) override; - - void PushLayer(const Rect& bounds) override; - - void PopLayer() override; - - void EndDraw() override final; - - protected: - virtual void DoEndDraw() = 0; - - private: - bool IsValid() { return is_drawing_; } - void CheckValidation(); - - private: - ID2D1RenderTarget* render_target_; - - std::vector> layers_; - - bool is_drawing_ = true; -}; -} // namespace cru::platform::graph::win::direct diff --git a/include/cru/win/graph/direct/Resource.hpp b/include/cru/win/graph/direct/Resource.hpp deleted file mode 100644 index 6162ebd8..00000000 --- a/include/cru/win/graph/direct/Resource.hpp +++ /dev/null @@ -1,49 +0,0 @@ -#pragma once -#include "../../WinPreConfig.hpp" - -#include "cru/platform/graph/Resource.hpp" - -#include - -namespace cru::platform::graph::win::direct { -class DirectGraphFactory; - -class DirectResource : public Object, public virtual INativeResource { - public: - static constexpr std::u16string_view k_platform_id = u"Windows Direct"; - - protected: - DirectResource() = default; - - public: - CRU_DELETE_COPY(DirectResource) - CRU_DELETE_MOVE(DirectResource) - - ~DirectResource() override = default; - - public: - std::u16string_view GetPlatformId() const final { return k_platform_id; } -}; - -class DirectGraphResource : public DirectResource, - public virtual IGraphResource { - protected: - // Param factory can't be null. - explicit DirectGraphResource(DirectGraphFactory* factory); - - public: - CRU_DELETE_COPY(DirectGraphResource) - CRU_DELETE_MOVE(DirectGraphResource) - - ~DirectGraphResource() override = default; - - public: - IGraphFactory* GetGraphFactory() final; - - public: - DirectGraphFactory* GetDirectFactory() const { return factory_; } - - private: - DirectGraphFactory* factory_; -}; -} // namespace cru::platform::graph::win::direct diff --git a/include/cru/win/graph/direct/TextLayout.hpp b/include/cru/win/graph/direct/TextLayout.hpp deleted file mode 100644 index 016009ab..00000000 --- a/include/cru/win/graph/direct/TextLayout.hpp +++ /dev/null @@ -1,55 +0,0 @@ -#pragma once -#include "ComResource.hpp" -#include "Resource.hpp" - -#include "cru/platform/graph/TextLayout.hpp" - -#include -#include - -namespace cru::platform::graph::win::direct { -class DWriteFont; - -class DWriteTextLayout : public DirectGraphResource, - public virtual ITextLayout, - public virtual IComResource { - public: - DWriteTextLayout(DirectGraphFactory* factory, std::shared_ptr font, - std::u16string text); - - CRU_DELETE_COPY(DWriteTextLayout) - CRU_DELETE_MOVE(DWriteTextLayout) - - ~DWriteTextLayout() override; - - public: - IDWriteTextLayout* GetComInterface() const override { - return text_layout_.Get(); - } - - public: - std::u16string GetText() override; - std::u16string_view GetTextView() override; - void SetText(std::u16string new_text) override; - - std::shared_ptr GetFont() override; - void SetFont(std::shared_ptr font) override; - - void SetMaxWidth(float max_width) override; - void SetMaxHeight(float max_height) override; - - Rect GetTextBounds() override; - // Return empty vector if text_range.count is 0. Text range could be in - // reverse direction, it should be normalized first in implementation. - std::vector TextRangeRect(const TextRange& text_range) override; - Point TextSinglePoint(Index position, bool trailing) override; - TextHitTestResult HitTest(const Point& point) override; - - private: - std::u16string text_; - std::shared_ptr font_; - float max_width_ = std::numeric_limits::max(); - float max_height_ = std::numeric_limits::max(); - Microsoft::WRL::ComPtr text_layout_; -}; -} // namespace cru::platform::graph::win::direct diff --git a/include/cru/win/graph/direct/WindowPainter.hpp b/include/cru/win/graph/direct/WindowPainter.hpp deleted file mode 100644 index 53961586..00000000 --- a/include/cru/win/graph/direct/WindowPainter.hpp +++ /dev/null @@ -1,21 +0,0 @@ -#pragma once -#include "Painter.hpp" -#include "WindowRenderTarget.hpp" - -namespace cru::platform::graph::win::direct { -class D2DWindowPainter : public graph::win::direct::D2DPainter { - public: - explicit D2DWindowPainter(D2DWindowRenderTarget* window); - - CRU_DELETE_COPY(D2DWindowPainter) - CRU_DELETE_MOVE(D2DWindowPainter) - - ~D2DWindowPainter() override; - - protected: - void DoEndDraw() override; - - private: - D2DWindowRenderTarget* render_target_; -}; -} // namespace cru::platform::graph::win::direct diff --git a/include/cru/win/graph/direct/WindowRenderTarget.hpp b/include/cru/win/graph/direct/WindowRenderTarget.hpp deleted file mode 100644 index c9ee098f..00000000 --- a/include/cru/win/graph/direct/WindowRenderTarget.hpp +++ /dev/null @@ -1,42 +0,0 @@ -#pragma once -#include "Factory.hpp" - -namespace cru::platform::graph::win::direct { -// Represents a window render target. -class D2DWindowRenderTarget : public Object { - public: - D2DWindowRenderTarget(gsl::not_null factory, HWND hwnd); - - CRU_DELETE_COPY(D2DWindowRenderTarget) - CRU_DELETE_MOVE(D2DWindowRenderTarget) - - ~D2DWindowRenderTarget() override = default; - - public: - graph::win::direct::DirectGraphFactory* GetDirectFactory() const { - return factory_; - } - - ID2D1DeviceContext* GetD2D1DeviceContext() { - return d2d1_device_context_.Get(); - } - - void SetDpi(float x, float y); - - // Resize the underlying buffer. - void ResizeBuffer(int width, int height); - - // Present the data of the underlying buffer to the window. - void Present(); - - private: - void CreateTargetBitmap(); - - private: - DirectGraphFactory* factory_; - HWND hwnd_; - Microsoft::WRL::ComPtr d2d1_device_context_; - Microsoft::WRL::ComPtr dxgi_swap_chain_; - Microsoft::WRL::ComPtr target_bitmap_; -}; -} // namespace cru::platform::graph::win::direct diff --git a/include/cru/win/graphics/direct/Brush.hpp b/include/cru/win/graphics/direct/Brush.hpp new file mode 100644 index 00000000..fbff83b5 --- /dev/null +++ b/include/cru/win/graphics/direct/Brush.hpp @@ -0,0 +1,39 @@ +#pragma once +#include "ComResource.hpp" +#include "Resource.hpp" + +#include "cru/platform/graphics/Brush.hpp" + +namespace cru::platform::graphics::win::direct { +struct ID2DBrush : virtual IBrush { + virtual ID2D1Brush* GetD2DBrushInterface() const = 0; +}; + +class D2DSolidColorBrush : public DirectGraphResource, + public virtual ISolidColorBrush, + public virtual ID2DBrush, + public virtual IComResource { + public: + explicit D2DSolidColorBrush(DirectGraphFactory* factory); + + CRU_DELETE_COPY(D2DSolidColorBrush) + CRU_DELETE_MOVE(D2DSolidColorBrush) + + ~D2DSolidColorBrush() override = default; + + public: + Color GetColor() override { return color_; } + void SetColor(const Color& color) override; + + ID2D1Brush* GetD2DBrushInterface() const override { return brush_.Get(); } + + ID2D1SolidColorBrush* GetComInterface() const override { + return brush_.Get(); + } + + private: + Color color_ = colors::black; + + Microsoft::WRL::ComPtr brush_; +}; +} // namespace cru::platform::graphics::win::direct diff --git a/include/cru/win/graphics/direct/ComResource.hpp b/include/cru/win/graphics/direct/ComResource.hpp new file mode 100644 index 00000000..34ea39ed --- /dev/null +++ b/include/cru/win/graphics/direct/ComResource.hpp @@ -0,0 +1,11 @@ +#pragma once +#include "../../WinPreConfig.hpp" + +#include "cru/common/Base.hpp" + +namespace cru::platform::graphics::win::direct { +template +struct IComResource : virtual Interface { + virtual TInterface* GetComInterface() const = 0; +}; +} // namespace cru::platform::graphics::win::direct diff --git a/include/cru/win/graphics/direct/ConvertUtil.hpp b/include/cru/win/graphics/direct/ConvertUtil.hpp new file mode 100644 index 00000000..0d8da8a1 --- /dev/null +++ b/include/cru/win/graphics/direct/ConvertUtil.hpp @@ -0,0 +1,107 @@ +#pragma once +#include "../../WinPreConfig.hpp" + +#include "cru/platform/graphics/Base.hpp" + +namespace cru::platform::graphics::win::direct { +inline D2D1_MATRIX_3X2_F Convert(const platform::Matrix& matrix) { + D2D1_MATRIX_3X2_F m; + m._11 = matrix.m11; + m._12 = matrix.m12; + m._21 = matrix.m21; + m._22 = matrix.m22; + m._31 = matrix.m31; + m._32 = matrix.m32; + return m; +} + +inline D2D1_COLOR_F Convert(const Color& color) { + return D2D1::ColorF(color.red / 255.0f, color.green / 255.0f, + color.blue / 255.0f, color.alpha / 255.0f); +} + +inline D2D1_POINT_2F Convert(const Point& point) { + return D2D1::Point2F(point.x, point.y); +} + +inline D2D1_RECT_F Convert(const Rect& rect) { + return D2D1::RectF(rect.left, rect.top, rect.left + rect.width, + rect.top + rect.height); +} + +inline D2D1_ROUNDED_RECT Convert(const RoundedRect& rounded_rect) { + return D2D1::RoundedRect(Convert(rounded_rect.rect), rounded_rect.radius_x, + rounded_rect.radius_y); +} + +inline D2D1_ELLIPSE Convert(const Ellipse& ellipse) { + return D2D1::Ellipse(Convert(ellipse.center), ellipse.radius_x, + ellipse.radius_y); +} + +inline platform::Matrix Convert(const D2D1_MATRIX_3X2_F& matrix) { + return platform::Matrix{matrix._11, matrix._12, matrix._21, + matrix._22, matrix._31, matrix._32}; +} + +inline Color Convert(const D2D1_COLOR_F& color) { + auto floor = [](float n) { return static_cast(n + 0.5f); }; + return Color{floor(color.r * 255.0f), floor(color.g * 255.0f), + floor(color.b * 255.0f), floor(color.a * 255.0f)}; +} + +inline Point Convert(const D2D1_POINT_2F& point) { + return Point(point.x, point.y); +} + +inline Rect Convert(const D2D1_RECT_F& rect) { + return Rect(rect.left, rect.top, rect.right - rect.left, + rect.bottom - rect.top); +} + +inline RoundedRect Convert(const D2D1_ROUNDED_RECT& rounded_rect) { + return RoundedRect(Convert(rounded_rect.rect), rounded_rect.radiusX, + rounded_rect.radiusY); +} + +inline Ellipse Convert(const D2D1_ELLIPSE& ellipse) { + return Ellipse(Convert(ellipse.point), ellipse.radiusX, ellipse.radiusY); +} + +inline bool operator==(const D2D1_POINT_2F& left, const D2D1_POINT_2F& right) { + return left.x == right.x && left.y == right.y; +} + +inline bool operator!=(const D2D1_POINT_2F& left, const D2D1_POINT_2F& right) { + return !(left == right); +} + +inline bool operator==(const D2D1_RECT_F& left, const D2D1_RECT_F& right) { + return left.left == right.left && left.top == right.top && + left.right == right.right && left.bottom == right.bottom; +} + +inline bool operator!=(const D2D1_RECT_F& left, const D2D1_RECT_F& right) { + return !(left == right); +} + +inline bool operator==(const D2D1_ROUNDED_RECT& left, + const D2D1_ROUNDED_RECT& right) { + return left.rect == right.rect && left.radiusX == right.radiusX && + left.radiusY == right.radiusY; +} + +inline bool operator!=(const D2D1_ROUNDED_RECT& left, + const D2D1_ROUNDED_RECT& right) { + return !(left == right); +} + +inline bool operator==(const D2D1_ELLIPSE& left, const D2D1_ELLIPSE& right) { + return left.point == right.point && left.radiusX == right.radiusX && + left.radiusY == right.radiusY; +} + +inline bool operator!=(const D2D1_ELLIPSE& left, const D2D1_ELLIPSE& right) { + return !(left == right); +} +} // namespace cru::platform::graphics::win::direct diff --git a/include/cru/win/graphics/direct/Exception.hpp b/include/cru/win/graphics/direct/Exception.hpp new file mode 100644 index 00000000..72493f2f --- /dev/null +++ b/include/cru/win/graphics/direct/Exception.hpp @@ -0,0 +1,7 @@ +#pragma once +#include "../../Exception.hpp" + +namespace cru::platform::graphics::win::direct { +using platform::win::HResultError; +using platform::win::ThrowIfFailed; +} // namespace cru::platform::graphics::win::direct diff --git a/include/cru/win/graphics/direct/Factory.hpp b/include/cru/win/graphics/direct/Factory.hpp new file mode 100644 index 00000000..70f3ede1 --- /dev/null +++ b/include/cru/win/graphics/direct/Factory.hpp @@ -0,0 +1,58 @@ +#pragma once +#include "Resource.hpp" + +#include "cru/platform/graphics/Factory.hpp" + +namespace cru::platform::graphics::win::direct { +class DirectGraphFactory : public DirectResource, public virtual IGraphFactory { + public: + DirectGraphFactory(); + + CRU_DELETE_COPY(DirectGraphFactory) + CRU_DELETE_MOVE(DirectGraphFactory) + + ~DirectGraphFactory() override; + + public: + ID3D11Device* GetD3D11Device() const { return d3d11_device_.Get(); } + ID2D1Factory1* GetD2D1Factory() const { return d2d1_factory_.Get(); } + ID2D1Device* GetD2D1Device() const { return d2d1_device_.Get(); } + IDXGIFactory2* GetDxgiFactory() const { return dxgi_factory_.Get(); } + IDWriteFactory* GetDWriteFactory() const { return dwrite_factory_.Get(); } + IDWriteFontCollection* GetSystemFontCollection() const { + return dwrite_system_font_collection_.Get(); + } + + public: + Microsoft::WRL::ComPtr CreateD2D1DeviceContext(); + + // This context should only be used to create graphic resources like brush. + // Because graphic resources can be shared if they are created in the same + // device. + ID2D1DeviceContext* GetDefaultD2D1DeviceContext() { + return d2d1_device_context_.Get(); + } + + public: + std::unique_ptr CreateSolidColorBrush() override; + + std::unique_ptr CreateGeometryBuilder() override; + + std::unique_ptr CreateFont(std::u16string font_family, + float font_size) override; + + std::unique_ptr CreateTextLayout(std::shared_ptr font, + std::u16string text) override; + + private: + Microsoft::WRL::ComPtr d3d11_device_; + // ID2D1Factory1 is a interface only available in Windows 8 and Windows 7 with + // update. It is d2d v1.1. + Microsoft::WRL::ComPtr d2d1_factory_; + Microsoft::WRL::ComPtr d2d1_device_; + Microsoft::WRL::ComPtr d2d1_device_context_; + Microsoft::WRL::ComPtr dxgi_factory_; + Microsoft::WRL::ComPtr dwrite_factory_; + Microsoft::WRL::ComPtr dwrite_system_font_collection_; +}; +} // namespace cru::platform::graphics::win::direct diff --git a/include/cru/win/graphics/direct/Font.hpp b/include/cru/win/graphics/direct/Font.hpp new file mode 100644 index 00000000..fd3921a3 --- /dev/null +++ b/include/cru/win/graphics/direct/Font.hpp @@ -0,0 +1,33 @@ +#pragma once +#include "ComResource.hpp" +#include "Resource.hpp" + +#include "cru/platform/graphics/Font.hpp" + +#include + +namespace cru::platform::graphics::win::direct { +class DWriteFont : public DirectGraphResource, + public virtual IFont, + public virtual IComResource { + public: + DWriteFont(DirectGraphFactory* factory, std::u16string font_family, + float font_size); + + CRU_DELETE_COPY(DWriteFont) + CRU_DELETE_MOVE(DWriteFont) + + ~DWriteFont() override = default; + + public: + IDWriteTextFormat* GetComInterface() const override { + return text_format_.Get(); + } + + float GetFontSize() override; + + private: + std::u16string font_family_; + Microsoft::WRL::ComPtr text_format_; +}; +} // namespace cru::platform::graphics::win::direct diff --git a/include/cru/win/graphics/direct/Geometry.hpp b/include/cru/win/graphics/direct/Geometry.hpp new file mode 100644 index 00000000..edfec590 --- /dev/null +++ b/include/cru/win/graphics/direct/Geometry.hpp @@ -0,0 +1,57 @@ +#pragma once +#include "ComResource.hpp" +#include "Resource.hpp" + +#include "cru/platform/graphics/Geometry.hpp" + +namespace cru::platform::graphics::win::direct { +class D2DGeometryBuilder : public DirectGraphResource, + public virtual IGeometryBuilder { + public: + explicit D2DGeometryBuilder(DirectGraphFactory* factory); + + CRU_DELETE_COPY(D2DGeometryBuilder) + CRU_DELETE_MOVE(D2DGeometryBuilder) + + ~D2DGeometryBuilder() override = default; + + public: + void BeginFigure(const Point& point) override; + void LineTo(const Point& point) override; + void QuadraticBezierTo(const Point& control_point, + const Point& end_point) override; + void CloseFigure(bool close) override; + + std::unique_ptr Build() override; + + private: + bool IsValid() { return geometry_ != nullptr; } + void CheckValidation(); + + private: + Microsoft::WRL::ComPtr geometry_; + Microsoft::WRL::ComPtr geometry_sink_; +}; + +class D2DGeometry : public DirectGraphResource, + public virtual IGeometry, + public IComResource { + public: + D2DGeometry(DirectGraphFactory* factory, + Microsoft::WRL::ComPtr geometry); + + CRU_DELETE_COPY(D2DGeometry) + CRU_DELETE_MOVE(D2DGeometry) + + ~D2DGeometry() override = default; + + public: + ID2D1Geometry* GetComInterface() const override { return geometry_.Get(); } + + public: + bool FillContains(const Point& point) override; + + private: + Microsoft::WRL::ComPtr geometry_; +}; +} // namespace cru::platform::graphics::win::direct diff --git a/include/cru/win/graphics/direct/Painter.hpp b/include/cru/win/graphics/direct/Painter.hpp new file mode 100644 index 00000000..93c768e7 --- /dev/null +++ b/include/cru/win/graphics/direct/Painter.hpp @@ -0,0 +1,60 @@ +#pragma once +#include "ComResource.hpp" +#include "Resource.hpp" + +#include "cru/platform/graphics/Painter.hpp" + +#include + +namespace cru::platform::graphics::win::direct { +class D2DPainter : public DirectResource, + public virtual IPainter, + public virtual IComResource { + public: + explicit D2DPainter(ID2D1RenderTarget* render_target); + + CRU_DELETE_COPY(D2DPainter) + CRU_DELETE_MOVE(D2DPainter) + + ~D2DPainter() override = default; + + public: + ID2D1RenderTarget* GetComInterface() const override { return render_target_; } + + public: + Matrix GetTransform() override; + void SetTransform(const platform::Matrix& matrix) override; + + void Clear(const Color& color) override; + + void StrokeRectangle(const Rect& rectangle, IBrush* brush, + float width) override; + void FillRectangle(const Rect& rectangle, IBrush* brush) override; + + void StrokeGeometry(IGeometry* geometry, IBrush* brush, float width) override; + void FillGeometry(IGeometry* geometry, IBrush* brush) override; + + void DrawText(const Point& offset, ITextLayout* text_layout, + IBrush* brush) override; + + void PushLayer(const Rect& bounds) override; + + void PopLayer() override; + + void EndDraw() override final; + + protected: + virtual void DoEndDraw() = 0; + + private: + bool IsValid() { return is_drawing_; } + void CheckValidation(); + + private: + ID2D1RenderTarget* render_target_; + + std::vector> layers_; + + bool is_drawing_ = true; +}; +} // namespace cru::platform::graphics::win::direct diff --git a/include/cru/win/graphics/direct/Resource.hpp b/include/cru/win/graphics/direct/Resource.hpp new file mode 100644 index 00000000..f60f373e --- /dev/null +++ b/include/cru/win/graphics/direct/Resource.hpp @@ -0,0 +1,49 @@ +#pragma once +#include "../../WinPreConfig.hpp" + +#include "cru/platform/graphics/Resource.hpp" + +#include + +namespace cru::platform::graphics::win::direct { +class DirectGraphFactory; + +class DirectResource : public Object, public virtual INativeResource { + public: + static constexpr std::u16string_view k_platform_id = u"Windows Direct"; + + protected: + DirectResource() = default; + + public: + CRU_DELETE_COPY(DirectResource) + CRU_DELETE_MOVE(DirectResource) + + ~DirectResource() override = default; + + public: + std::u16string_view GetPlatformId() const final { return k_platform_id; } +}; + +class DirectGraphResource : public DirectResource, + public virtual IGraphResource { + protected: + // Param factory can't be null. + explicit DirectGraphResource(DirectGraphFactory* factory); + + public: + CRU_DELETE_COPY(DirectGraphResource) + CRU_DELETE_MOVE(DirectGraphResource) + + ~DirectGraphResource() override = default; + + public: + IGraphFactory* GetGraphFactory() final; + + public: + DirectGraphFactory* GetDirectFactory() const { return factory_; } + + private: + DirectGraphFactory* factory_; +}; +} // namespace cru::platform::graphics::win::direct diff --git a/include/cru/win/graphics/direct/TextLayout.hpp b/include/cru/win/graphics/direct/TextLayout.hpp new file mode 100644 index 00000000..3320431f --- /dev/null +++ b/include/cru/win/graphics/direct/TextLayout.hpp @@ -0,0 +1,55 @@ +#pragma once +#include "ComResource.hpp" +#include "Resource.hpp" + +#include "cru/platform/graphics/TextLayout.hpp" + +#include +#include + +namespace cru::platform::graphics::win::direct { +class DWriteFont; + +class DWriteTextLayout : public DirectGraphResource, + public virtual ITextLayout, + public virtual IComResource { + public: + DWriteTextLayout(DirectGraphFactory* factory, std::shared_ptr font, + std::u16string text); + + CRU_DELETE_COPY(DWriteTextLayout) + CRU_DELETE_MOVE(DWriteTextLayout) + + ~DWriteTextLayout() override; + + public: + IDWriteTextLayout* GetComInterface() const override { + return text_layout_.Get(); + } + + public: + std::u16string GetText() override; + std::u16string_view GetTextView() override; + void SetText(std::u16string new_text) override; + + std::shared_ptr GetFont() override; + void SetFont(std::shared_ptr font) override; + + void SetMaxWidth(float max_width) override; + void SetMaxHeight(float max_height) override; + + Rect GetTextBounds() override; + // Return empty vector if text_range.count is 0. Text range could be in + // reverse direction, it should be normalized first in implementation. + std::vector TextRangeRect(const TextRange& text_range) override; + Point TextSinglePoint(Index position, bool trailing) override; + TextHitTestResult HitTest(const Point& point) override; + + private: + std::u16string text_; + std::shared_ptr font_; + float max_width_ = std::numeric_limits::max(); + float max_height_ = std::numeric_limits::max(); + Microsoft::WRL::ComPtr text_layout_; +}; +} // namespace cru::platform::graphics::win::direct diff --git a/include/cru/win/graphics/direct/WindowPainter.hpp b/include/cru/win/graphics/direct/WindowPainter.hpp new file mode 100644 index 00000000..b5faf7b5 --- /dev/null +++ b/include/cru/win/graphics/direct/WindowPainter.hpp @@ -0,0 +1,21 @@ +#pragma once +#include "Painter.hpp" +#include "WindowRenderTarget.hpp" + +namespace cru::platform::graphics::win::direct { +class D2DWindowPainter : public graphics::win::direct::D2DPainter { + public: + explicit D2DWindowPainter(D2DWindowRenderTarget* window); + + CRU_DELETE_COPY(D2DWindowPainter) + CRU_DELETE_MOVE(D2DWindowPainter) + + ~D2DWindowPainter() override; + + protected: + void DoEndDraw() override; + + private: + D2DWindowRenderTarget* render_target_; +}; +} // namespace cru::platform::graphics::win::direct diff --git a/include/cru/win/graphics/direct/WindowRenderTarget.hpp b/include/cru/win/graphics/direct/WindowRenderTarget.hpp new file mode 100644 index 00000000..75b1bf20 --- /dev/null +++ b/include/cru/win/graphics/direct/WindowRenderTarget.hpp @@ -0,0 +1,42 @@ +#pragma once +#include "Factory.hpp" + +namespace cru::platform::graphics::win::direct { +// Represents a window render target. +class D2DWindowRenderTarget : public Object { + public: + D2DWindowRenderTarget(gsl::not_null factory, HWND hwnd); + + CRU_DELETE_COPY(D2DWindowRenderTarget) + CRU_DELETE_MOVE(D2DWindowRenderTarget) + + ~D2DWindowRenderTarget() override = default; + + public: + graphics::win::direct::DirectGraphFactory* GetDirectFactory() const { + return factory_; + } + + ID2D1DeviceContext* GetD2D1DeviceContext() { + return d2d1_device_context_.Get(); + } + + void SetDpi(float x, float y); + + // Resize the underlying buffer. + void ResizeBuffer(int width, int height); + + // Present the data of the underlying buffer to the window. + void Present(); + + private: + void CreateTargetBitmap(); + + private: + DirectGraphFactory* factory_; + HWND hwnd_; + Microsoft::WRL::ComPtr d2d1_device_context_; + Microsoft::WRL::ComPtr dxgi_swap_chain_; + Microsoft::WRL::ComPtr target_bitmap_; +}; +} // namespace cru::platform::graphics::win::direct diff --git a/include/cru/win/gui/Base.hpp b/include/cru/win/gui/Base.hpp new file mode 100644 index 00000000..00782663 --- /dev/null +++ b/include/cru/win/gui/Base.hpp @@ -0,0 +1,16 @@ +#pragma once +#include "../WinPreConfig.hpp" + +#include "cru/common/Base.hpp" + +namespace cru::platform::gui::win { +class GodWindow; +class TimerManager; +class WinCursor; +class WinCursorManager; +class WindowClass; +class WindowManager; +class WinNativeWindow; +class WinUiApplication; +class WinInputMethodContext; +} // namespace cru::platform::gui::win diff --git a/include/cru/win/gui/Cursor.hpp b/include/cru/win/gui/Cursor.hpp new file mode 100644 index 00000000..cd13ded7 --- /dev/null +++ b/include/cru/win/gui/Cursor.hpp @@ -0,0 +1,49 @@ +#pragma once +#include "Resource.hpp" + +#include "cru/platform/gui/Cursor.hpp" + +#include + +namespace cru::platform::gui::win { +class WinCursor : public WinNativeResource, public virtual ICursor { + CRU_DEFINE_CLASS_LOG_TAG(u"cru::platform::gui::win::WinCursor") + + public: + WinCursor(HCURSOR handle, bool auto_destroy); + + CRU_DELETE_COPY(WinCursor) + CRU_DELETE_MOVE(WinCursor) + + ~WinCursor() override; + + public: + HCURSOR GetHandle() const { return handle_; } + + private: + HCURSOR handle_; + bool auto_destroy_; +}; + +class WinCursorManager : public WinNativeResource, + public virtual ICursorManager { + public: + WinCursorManager(); + + CRU_DELETE_COPY(WinCursorManager) + CRU_DELETE_MOVE(WinCursorManager) + + ~WinCursorManager() override = default; + + public: + std::shared_ptr GetSystemWinCursor(SystemCursorType type); + + std::shared_ptr GetSystemCursor(SystemCursorType type) override { + return std::static_pointer_cast(GetSystemWinCursor(type)); + } + + private: + std::shared_ptr sys_arrow_; + std::shared_ptr sys_hand_; +}; +} // namespace cru::platform::gui::win diff --git a/include/cru/win/gui/Exception.hpp b/include/cru/win/gui/Exception.hpp new file mode 100644 index 00000000..895e6c14 --- /dev/null +++ b/include/cru/win/gui/Exception.hpp @@ -0,0 +1,7 @@ +#pragma once +#include "../Exception.hpp" + +namespace cru::platform::gui::win { +using platform::win::Win32Error; +using platform::win::HResultError; +} // namespace cru::platform::gui::win diff --git a/include/cru/win/gui/GodWindow.hpp b/include/cru/win/gui/GodWindow.hpp new file mode 100644 index 00000000..0343b159 --- /dev/null +++ b/include/cru/win/gui/GodWindow.hpp @@ -0,0 +1,38 @@ +#pragma once +#include "Base.hpp" + +#include "WindowNativeMessageEventArgs.hpp" +#include "cru/common/Event.hpp" + +#include + +namespace cru::platform::gui::win { +class GodWindow : public Object { + CRU_DEFINE_CLASS_LOG_TAG(u"cru::platform::gui::win::GodWindow") + + public: + explicit GodWindow(WinUiApplication* application); + + CRU_DELETE_COPY(GodWindow) + CRU_DELETE_MOVE(GodWindow) + + ~GodWindow() override; + + HWND GetHandle() const { return hwnd_; } + + bool HandleGodWindowMessage(HWND hwnd, UINT msg, WPARAM w_param, + LPARAM l_param, LRESULT* result); + + IEvent* MessageEvent() { + return &message_event_; + } + + private: + WinUiApplication* application_; + + std::unique_ptr god_window_class_; + HWND hwnd_; + + Event message_event_; +}; +} // namespace cru::platform::gui::win diff --git a/include/cru/win/gui/InputMethod.hpp b/include/cru/win/gui/InputMethod.hpp new file mode 100644 index 00000000..51a007d8 --- /dev/null +++ b/include/cru/win/gui/InputMethod.hpp @@ -0,0 +1,87 @@ +// Some useful information can be found from chromium code: +// https://chromium.googlesource.com/chromium/chromium/+/refs/heads/master/ui/base/win/ime_input.h +// https://chromium.googlesource.com/chromium/chromium/+/refs/heads/master/ui/base/win/ime_input.cc + +#pragma once +#include "Resource.hpp" + +#include "WindowNativeMessageEventArgs.hpp" +#include "cru/platform/gui/InputMethod.hpp" + +#include + +namespace cru::platform::gui::win { +class AutoHIMC : public Object { + CRU_DEFINE_CLASS_LOG_TAG(u"cru::platform::gui::win::AutoHIMC") + + public: + explicit AutoHIMC(HWND hwnd); + + CRU_DELETE_COPY(AutoHIMC) + + AutoHIMC(AutoHIMC&& other); + AutoHIMC& operator=(AutoHIMC&& other); + + ~AutoHIMC() override; + + HWND GetHwnd() const { return hwnd_; } + + HIMC Get() const { return handle_; } + + private: + HWND hwnd_; + HIMC handle_; +}; + +class WinInputMethodContext : public WinNativeResource, + public virtual IInputMethodContext { + CRU_DEFINE_CLASS_LOG_TAG(u"cru::platform::gui::win::WinInputMethodContext") + + public: + WinInputMethodContext(gsl::not_null window); + + CRU_DELETE_COPY(WinInputMethodContext) + CRU_DELETE_MOVE(WinInputMethodContext) + + ~WinInputMethodContext() override; + + bool ShouldManuallyDrawCompositionText() override { return true; } + + void EnableIME() override; + + void DisableIME() override; + + void CompleteComposition() override; + + void CancelComposition() override; + + CompositionText GetCompositionText() override; + + void SetCandidateWindowPosition(const Point& point) override; + + IEvent* CompositionStartEvent() override; + + IEvent* CompositionEndEvent() override; + + IEvent* CompositionEvent() override; + + IEvent* TextEvent() override; + + private: + void OnWindowNativeMessage(WindowNativeMessageEventArgs& args); + + std::u16string GetResultString(); + + AutoHIMC GetHIMC(); + + private: + WinNativeWindow* native_window_; + + EventRevokerListGuard event_guard_; + + Event composition_start_event_; + Event composition_end_event_; + Event composition_event_; + Event text_event_; +}; +} // namespace cru::platform::gui::win diff --git a/include/cru/win/gui/Keyboard.hpp b/include/cru/win/gui/Keyboard.hpp new file mode 100644 index 00000000..5b98833c --- /dev/null +++ b/include/cru/win/gui/Keyboard.hpp @@ -0,0 +1,9 @@ +#pragma once +#include "Base.hpp" + +#include "cru/platform/gui/Keyboard.hpp" + +namespace cru::platform::gui::win { +KeyCode VirtualKeyToKeyCode(int virtual_key); +KeyModifier RetrieveKeyMofifier(); +} // namespace cru::platform::gui::win diff --git a/include/cru/win/gui/Resource.hpp b/include/cru/win/gui/Resource.hpp new file mode 100644 index 00000000..1f6f0a4a --- /dev/null +++ b/include/cru/win/gui/Resource.hpp @@ -0,0 +1,23 @@ +#pragma once +#include "Base.hpp" + +#include "cru/platform/Resource.hpp" + +namespace cru::platform::gui::win { +class WinNativeResource : public Object, public virtual INativeResource { + public: + static constexpr std::u16string_view k_platform_id = u"Windows"; + + protected: + WinNativeResource() = default; + + public: + CRU_DELETE_COPY(WinNativeResource) + CRU_DELETE_MOVE(WinNativeResource) + + ~WinNativeResource() override = default; + + public: + std::u16string_view GetPlatformId() const final { return k_platform_id; } +}; +} // namespace cru::platform::gui::win diff --git a/include/cru/win/gui/UiApplication.hpp b/include/cru/win/gui/UiApplication.hpp new file mode 100644 index 00000000..0f733cd4 --- /dev/null +++ b/include/cru/win/gui/UiApplication.hpp @@ -0,0 +1,74 @@ +#pragma once +#include "Resource.hpp" + +#include "cru/platform/gui/Base.hpp" +#include "cru/platform/gui/UiApplication.hpp" + +#include + +namespace cru::platform::graphics::win::direct { +class DirectGraphFactory; +} + +namespace cru::platform::gui::win { +class WinUiApplication : public WinNativeResource, + public virtual IUiApplication { + public: + static WinUiApplication* GetInstance() { return instance; } + + private: + static WinUiApplication* instance; + + public: + WinUiApplication(); + + CRU_DELETE_COPY(WinUiApplication) + CRU_DELETE_MOVE(WinUiApplication) + + ~WinUiApplication() override; + + public: + int Run() override; + void RequestQuit(int quit_code) override; + + void AddOnQuitHandler(std::function handler) override; + + long long SetImmediate(std::function action) override; + long long SetTimeout(std::chrono::milliseconds milliseconds, + std::function action) override; + long long SetInterval(std::chrono::milliseconds milliseconds, + std::function action) override; + void CancelTimer(long long id) override; + + std::vector GetAllWindow() override; + INativeWindow* CreateWindow(INativeWindow* parent) override; + + cru::platform::graphics::IGraphFactory* GetGraphFactory() override; + + cru::platform::graphics::win::direct::DirectGraphFactory* GetDirectFactory() { + return graph_factory_.get(); + } + + ICursorManager* GetCursorManager() override; + + HINSTANCE GetInstanceHandle() const { return instance_handle_; } + + GodWindow* GetGodWindow() const { return god_window_.get(); } + TimerManager* GetTimerManager() const { return timer_manager_.get(); } + WindowManager* GetWindowManager() const { return window_manager_.get(); } + + private: + HINSTANCE instance_handle_; + + std::unique_ptr + graph_factory_; + + std::unique_ptr god_window_; + std::unique_ptr timer_manager_; + std::unique_ptr window_manager_; + + std::unique_ptr cursor_manager_; + + std::vector> quit_handlers_; +}; +} // namespace cru::platform::gui::win diff --git a/include/cru/win/gui/Window.hpp b/include/cru/win/gui/Window.hpp new file mode 100644 index 00000000..3ba9ef68 --- /dev/null +++ b/include/cru/win/gui/Window.hpp @@ -0,0 +1,178 @@ +#pragma once +#include "Resource.hpp" + +#include "WindowNativeMessageEventArgs.hpp" +#include "cru/platform/GraphBase.hpp" +#include "cru/platform/gui/Base.hpp" +#include "cru/platform/gui/Window.hpp" +#include "cru/win/graphics/direct/WindowRenderTarget.hpp" + +#include + +namespace cru::platform::gui::win { +class WinNativeWindow : public WinNativeResource, public virtual INativeWindow { + CRU_DEFINE_CLASS_LOG_TAG(u"cru::platform::gui::win::WinNativeWindow") + + public: + WinNativeWindow(WinUiApplication* application, WindowClass* window_class, + DWORD window_style, WinNativeWindow* parent); + + CRU_DELETE_COPY(WinNativeWindow) + CRU_DELETE_MOVE(WinNativeWindow) + + ~WinNativeWindow() override; + + public: + void Close() override; + + WinNativeWindow* GetParent() override { return parent_window_; } + + bool IsVisible() override; + void SetVisible(bool is_visible) override; + + Size GetClientSize() override; + void SetClientSize(const Size& size) override; + + // Get the rect of the window containing frame. + // The lefttop of the rect is relative to screen lefttop. + Rect GetWindowRect() override; + + // Set the rect of the window containing frame. + // The lefttop of the rect is relative to screen lefttop. + void SetWindowRect(const Rect& rect) override; + + Point GetMousePosition() override; + + bool CaptureMouse() override; + bool ReleaseMouse() override; + + void RequestRepaint() override; + std::unique_ptr BeginPaint() override; + + void SetCursor(std::shared_ptr cursor) override; + + IEvent* DestroyEvent() override { return &destroy_event_; } + IEvent* PaintEvent() override { return &paint_event_; } + IEvent* ResizeEvent() override { return &resize_event_; } + IEvent* FocusEvent() override { return &focus_event_; } + IEvent* MouseEnterLeaveEvent() override { + return &mouse_enter_leave_event_; + } + IEvent* MouseMoveEvent() override { return &mouse_move_event_; } + IEvent* MouseDownEvent() + override { + return &mouse_down_event_; + } + IEvent* MouseUpEvent() + override { + return &mouse_up_event_; + } + IEvent* KeyDownEvent() override { + return &key_down_event_; + } + IEvent* KeyUpEvent() override { + return &key_up_event_; + } + + IEvent* NativeMessageEvent() { + return &native_message_event_; + } + + IInputMethodContext* GetInputMethodContext() override; + + // Get the handle of the window. Return null if window is invalid. + HWND GetWindowHandle() const { return hwnd_; } + + bool HandleNativeWindowMessage(HWND hwnd, UINT msg, WPARAM w_param, + LPARAM l_param, LRESULT* result); + + graphics::win::direct::D2DWindowRenderTarget* GetWindowRenderTarget() const { + return window_render_target_.get(); + } + + //*************** region: dpi *************** + float GetDpi() const { return dpi_; } + + inline int DipToPixel(const float dip) { + return static_cast(dip * GetDpi() / 96.0f); + } + + inline POINT DipToPixel(const Point& dip_point) { + POINT result; + result.x = DipToPixel(dip_point.x); + result.y = DipToPixel(dip_point.y); + return result; + } + + inline float PixelToDip(const int pixel) { + return static_cast(pixel) * 96.0f / GetDpi(); + } + + inline Point PixelToDip(const POINT& pi_point) { + return Point(PixelToDip(pi_point.x), PixelToDip(pi_point.y)); + } + + private: + // Get the client rect in pixel. + RECT GetClientRectPixel(); + + //*************** region: native messages *************** + + void OnDestroyInternal(); + void OnPaintInternal(); + void OnResizeInternal(int new_width, int new_height); + + void OnSetFocusInternal(); + void OnKillFocusInternal(); + + void OnMouseMoveInternal(POINT point); + void OnMouseLeaveInternal(); + void OnMouseDownInternal(platform::gui::MouseButton button, POINT point); + void OnMouseUpInternal(platform::gui::MouseButton button, POINT point); + + void OnMouseWheelInternal(short delta, POINT point); + void OnKeyDownInternal(int virtual_code); + void OnKeyUpInternal(int virtual_code); + + void OnActivatedInternal(); + void OnDeactivatedInternal(); + + private: + WinUiApplication* application_; + + // when delete is called first, it set this to true to indicate + // destroy message handler not to double delete this instance; + // when destroy handler is called first (by user action or method + // Close), it set this to true to indicate delete not call Close + // again. + bool sync_flag_ = false; + + HWND hwnd_; + WinNativeWindow* parent_window_; + + float dpi_; + + bool has_focus_ = false; + bool is_mouse_in_ = false; + + std::unique_ptr + window_render_target_; + + std::shared_ptr cursor_; + + std::unique_ptr input_method_context_; + + Event destroy_event_; + Event paint_event_; + Event resize_event_; + Event focus_event_; + Event mouse_enter_leave_event_; + Event mouse_move_event_; + Event mouse_down_event_; + Event mouse_up_event_; + Event key_down_event_; + Event key_up_event_; + + Event native_message_event_; +}; +} // namespace cru::platform::gui::win diff --git a/include/cru/win/gui/WindowClass.hpp b/include/cru/win/gui/WindowClass.hpp new file mode 100644 index 00000000..2c07b68f --- /dev/null +++ b/include/cru/win/gui/WindowClass.hpp @@ -0,0 +1,24 @@ +#pragma once +#include "Base.hpp" + +#include + +namespace cru::platform::gui::win { +class WindowClass : public Object { + public: + WindowClass(std::wstring name, WNDPROC window_proc, HINSTANCE h_instance); + + CRU_DELETE_COPY(WindowClass) + CRU_DELETE_MOVE(WindowClass) + + ~WindowClass() override = default; + + const wchar_t* GetName() const { return name_.c_str(); } + + ATOM GetAtom() const { return atom_; } + + private: + std::wstring name_; + ATOM atom_; +}; +} // namespace cru::platform::gui::win diff --git a/include/cru/win/gui/WindowNativeMessageEventArgs.hpp b/include/cru/win/gui/WindowNativeMessageEventArgs.hpp new file mode 100644 index 00000000..834ba3c2 --- /dev/null +++ b/include/cru/win/gui/WindowNativeMessageEventArgs.hpp @@ -0,0 +1,40 @@ +#pragma once +#include "../WinPreConfig.hpp" + +#include "cru/common/Base.hpp" + +namespace cru::platform::gui::win { +struct WindowNativeMessage { + HWND hwnd; + UINT msg; + WPARAM w_param; + LPARAM l_param; +}; + +class WindowNativeMessageEventArgs : public Object { + public: + WindowNativeMessageEventArgs(const WindowNativeMessage& message) + : message_(message) {} + CRU_DEFAULT_COPY(WindowNativeMessageEventArgs) + CRU_DEFAULT_MOVE(WindowNativeMessageEventArgs) + ~WindowNativeMessageEventArgs() override = default; + + const WindowNativeMessage& GetWindowMessage() const { return message_; } + + LRESULT GetResult() const { return result_; } + void SetResult(LRESULT result) { result_ = result; } + + bool IsHandled() const { return handled_; } + void SetHandled(bool handled) { handled_ = handled; } + + void HandleWithResult(LRESULT result) { + handled_ = true; + result_ = result; + } + + private: + WindowNativeMessage message_; + LRESULT result_; + bool handled_ = false; +}; +} // namespace cru::platform::gui::win diff --git a/include/cru/win/native/Base.hpp b/include/cru/win/native/Base.hpp deleted file mode 100644 index 881dd8b1..00000000 --- a/include/cru/win/native/Base.hpp +++ /dev/null @@ -1,16 +0,0 @@ -#pragma once -#include "../WinPreConfig.hpp" - -#include "cru/common/Base.hpp" - -namespace cru::platform::native::win { -class GodWindow; -class TimerManager; -class WinCursor; -class WinCursorManager; -class WindowClass; -class WindowManager; -class WinNativeWindow; -class WinUiApplication; -class WinInputMethodContext; -} // namespace cru::platform::native::win diff --git a/include/cru/win/native/Cursor.hpp b/include/cru/win/native/Cursor.hpp deleted file mode 100644 index 373b9170..00000000 --- a/include/cru/win/native/Cursor.hpp +++ /dev/null @@ -1,49 +0,0 @@ -#pragma once -#include "Resource.hpp" - -#include "cru/platform/native/Cursor.hpp" - -#include - -namespace cru::platform::native::win { -class WinCursor : public WinNativeResource, public virtual ICursor { - CRU_DEFINE_CLASS_LOG_TAG(u"cru::platform::native::win::WinCursor") - - public: - WinCursor(HCURSOR handle, bool auto_destroy); - - CRU_DELETE_COPY(WinCursor) - CRU_DELETE_MOVE(WinCursor) - - ~WinCursor() override; - - public: - HCURSOR GetHandle() const { return handle_; } - - private: - HCURSOR handle_; - bool auto_destroy_; -}; - -class WinCursorManager : public WinNativeResource, - public virtual ICursorManager { - public: - WinCursorManager(); - - CRU_DELETE_COPY(WinCursorManager) - CRU_DELETE_MOVE(WinCursorManager) - - ~WinCursorManager() override = default; - - public: - std::shared_ptr GetSystemWinCursor(SystemCursorType type); - - std::shared_ptr GetSystemCursor(SystemCursorType type) override { - return std::static_pointer_cast(GetSystemWinCursor(type)); - } - - private: - std::shared_ptr sys_arrow_; - std::shared_ptr sys_hand_; -}; -} // namespace cru::platform::native::win diff --git a/include/cru/win/native/Exception.hpp b/include/cru/win/native/Exception.hpp deleted file mode 100644 index 6a5265c1..00000000 --- a/include/cru/win/native/Exception.hpp +++ /dev/null @@ -1,7 +0,0 @@ -#pragma once -#include "../Exception.hpp" - -namespace cru::platform::native::win { -using platform::win::Win32Error; -using platform::win::HResultError; -} // namespace cru::platform::native::win diff --git a/include/cru/win/native/GodWindow.hpp b/include/cru/win/native/GodWindow.hpp deleted file mode 100644 index 93d1acad..00000000 --- a/include/cru/win/native/GodWindow.hpp +++ /dev/null @@ -1,38 +0,0 @@ -#pragma once -#include "Base.hpp" - -#include "WindowNativeMessageEventArgs.hpp" -#include "cru/common/Event.hpp" - -#include - -namespace cru::platform::native::win { -class GodWindow : public Object { - CRU_DEFINE_CLASS_LOG_TAG(u"cru::platform::native::win::GodWindow") - - public: - explicit GodWindow(WinUiApplication* application); - - CRU_DELETE_COPY(GodWindow) - CRU_DELETE_MOVE(GodWindow) - - ~GodWindow() override; - - HWND GetHandle() const { return hwnd_; } - - bool HandleGodWindowMessage(HWND hwnd, UINT msg, WPARAM w_param, - LPARAM l_param, LRESULT* result); - - IEvent* MessageEvent() { - return &message_event_; - } - - private: - WinUiApplication* application_; - - std::unique_ptr god_window_class_; - HWND hwnd_; - - Event message_event_; -}; -} // namespace cru::platform::native::win diff --git a/include/cru/win/native/InputMethod.hpp b/include/cru/win/native/InputMethod.hpp deleted file mode 100644 index f3dc15c0..00000000 --- a/include/cru/win/native/InputMethod.hpp +++ /dev/null @@ -1,87 +0,0 @@ -// Some useful information can be found from chromium code: -// https://chromium.googlesource.com/chromium/chromium/+/refs/heads/master/ui/base/win/ime_input.h -// https://chromium.googlesource.com/chromium/chromium/+/refs/heads/master/ui/base/win/ime_input.cc - -#pragma once -#include "Resource.hpp" - -#include "WindowNativeMessageEventArgs.hpp" -#include "cru/platform/native/InputMethod.hpp" - -#include - -namespace cru::platform::native::win { -class AutoHIMC : public Object { - CRU_DEFINE_CLASS_LOG_TAG(u"cru::platform::native::win::AutoHIMC") - - public: - explicit AutoHIMC(HWND hwnd); - - CRU_DELETE_COPY(AutoHIMC) - - AutoHIMC(AutoHIMC&& other); - AutoHIMC& operator=(AutoHIMC&& other); - - ~AutoHIMC() override; - - HWND GetHwnd() const { return hwnd_; } - - HIMC Get() const { return handle_; } - - private: - HWND hwnd_; - HIMC handle_; -}; - -class WinInputMethodContext : public WinNativeResource, - public virtual IInputMethodContext { - CRU_DEFINE_CLASS_LOG_TAG(u"cru::platform::native::win::WinInputMethodContext") - - public: - WinInputMethodContext(gsl::not_null window); - - CRU_DELETE_COPY(WinInputMethodContext) - CRU_DELETE_MOVE(WinInputMethodContext) - - ~WinInputMethodContext() override; - - bool ShouldManuallyDrawCompositionText() override { return true; } - - void EnableIME() override; - - void DisableIME() override; - - void CompleteComposition() override; - - void CancelComposition() override; - - CompositionText GetCompositionText() override; - - void SetCandidateWindowPosition(const Point& point) override; - - IEvent* CompositionStartEvent() override; - - IEvent* CompositionEndEvent() override; - - IEvent* CompositionEvent() override; - - IEvent* TextEvent() override; - - private: - void OnWindowNativeMessage(WindowNativeMessageEventArgs& args); - - std::u16string GetResultString(); - - AutoHIMC GetHIMC(); - - private: - WinNativeWindow* native_window_; - - EventRevokerListGuard event_guard_; - - Event composition_start_event_; - Event composition_end_event_; - Event composition_event_; - Event text_event_; -}; -} // namespace cru::platform::native::win diff --git a/include/cru/win/native/Keyboard.hpp b/include/cru/win/native/Keyboard.hpp deleted file mode 100644 index 790e0015..00000000 --- a/include/cru/win/native/Keyboard.hpp +++ /dev/null @@ -1,9 +0,0 @@ -#pragma once -#include "Base.hpp" - -#include "cru/platform/native/Keyboard.hpp" - -namespace cru::platform::native::win { -KeyCode VirtualKeyToKeyCode(int virtual_key); -KeyModifier RetrieveKeyMofifier(); -} // namespace cru::platform::native::win diff --git a/include/cru/win/native/Resource.hpp b/include/cru/win/native/Resource.hpp deleted file mode 100644 index 0de0e1a8..00000000 --- a/include/cru/win/native/Resource.hpp +++ /dev/null @@ -1,23 +0,0 @@ -#pragma once -#include "Base.hpp" - -#include "cru/platform/Resource.hpp" - -namespace cru::platform::native::win { -class WinNativeResource : public Object, public virtual INativeResource { - public: - static constexpr std::u16string_view k_platform_id = u"Windows"; - - protected: - WinNativeResource() = default; - - public: - CRU_DELETE_COPY(WinNativeResource) - CRU_DELETE_MOVE(WinNativeResource) - - ~WinNativeResource() override = default; - - public: - std::u16string_view GetPlatformId() const final { return k_platform_id; } -}; -} // namespace cru::platform::native::win diff --git a/include/cru/win/native/UiApplication.hpp b/include/cru/win/native/UiApplication.hpp deleted file mode 100644 index 170be532..00000000 --- a/include/cru/win/native/UiApplication.hpp +++ /dev/null @@ -1,74 +0,0 @@ -#pragma once -#include "Resource.hpp" - -#include "cru/platform/native/Base.hpp" -#include "cru/platform/native/UiApplication.hpp" - -#include - -namespace cru::platform::graph::win::direct { -class DirectGraphFactory; -} - -namespace cru::platform::native::win { -class WinUiApplication : public WinNativeResource, - public virtual IUiApplication { - public: - static WinUiApplication* GetInstance() { return instance; } - - private: - static WinUiApplication* instance; - - public: - WinUiApplication(); - - CRU_DELETE_COPY(WinUiApplication) - CRU_DELETE_MOVE(WinUiApplication) - - ~WinUiApplication() override; - - public: - int Run() override; - void RequestQuit(int quit_code) override; - - void AddOnQuitHandler(std::function handler) override; - - long long SetImmediate(std::function action) override; - long long SetTimeout(std::chrono::milliseconds milliseconds, - std::function action) override; - long long SetInterval(std::chrono::milliseconds milliseconds, - std::function action) override; - void CancelTimer(long long id) override; - - std::vector GetAllWindow() override; - INativeWindow* CreateWindow(INativeWindow* parent) override; - - cru::platform::graph::IGraphFactory* GetGraphFactory() override; - - cru::platform::graph::win::direct::DirectGraphFactory* GetDirectFactory() { - return graph_factory_.get(); - } - - ICursorManager* GetCursorManager() override; - - HINSTANCE GetInstanceHandle() const { return instance_handle_; } - - GodWindow* GetGodWindow() const { return god_window_.get(); } - TimerManager* GetTimerManager() const { return timer_manager_.get(); } - WindowManager* GetWindowManager() const { return window_manager_.get(); } - - private: - HINSTANCE instance_handle_; - - std::unique_ptr - graph_factory_; - - std::unique_ptr god_window_; - std::unique_ptr timer_manager_; - std::unique_ptr window_manager_; - - std::unique_ptr cursor_manager_; - - std::vector> quit_handlers_; -}; -} // namespace cru::platform::native::win diff --git a/include/cru/win/native/Window.hpp b/include/cru/win/native/Window.hpp deleted file mode 100644 index 6bf71601..00000000 --- a/include/cru/win/native/Window.hpp +++ /dev/null @@ -1,178 +0,0 @@ -#pragma once -#include "Resource.hpp" - -#include "WindowNativeMessageEventArgs.hpp" -#include "cru/platform/GraphBase.hpp" -#include "cru/platform/native/Base.hpp" -#include "cru/platform/native/Window.hpp" -#include "cru/win/graph/direct/WindowRenderTarget.hpp" - -#include - -namespace cru::platform::native::win { -class WinNativeWindow : public WinNativeResource, public virtual INativeWindow { - CRU_DEFINE_CLASS_LOG_TAG(u"cru::platform::native::win::WinNativeWindow") - - public: - WinNativeWindow(WinUiApplication* application, WindowClass* window_class, - DWORD window_style, WinNativeWindow* parent); - - CRU_DELETE_COPY(WinNativeWindow) - CRU_DELETE_MOVE(WinNativeWindow) - - ~WinNativeWindow() override; - - public: - void Close() override; - - WinNativeWindow* GetParent() override { return parent_window_; } - - bool IsVisible() override; - void SetVisible(bool is_visible) override; - - Size GetClientSize() override; - void SetClientSize(const Size& size) override; - - // Get the rect of the window containing frame. - // The lefttop of the rect is relative to screen lefttop. - Rect GetWindowRect() override; - - // Set the rect of the window containing frame. - // The lefttop of the rect is relative to screen lefttop. - void SetWindowRect(const Rect& rect) override; - - Point GetMousePosition() override; - - bool CaptureMouse() override; - bool ReleaseMouse() override; - - void RequestRepaint() override; - std::unique_ptr BeginPaint() override; - - void SetCursor(std::shared_ptr cursor) override; - - IEvent* DestroyEvent() override { return &destroy_event_; } - IEvent* PaintEvent() override { return &paint_event_; } - IEvent* ResizeEvent() override { return &resize_event_; } - IEvent* FocusEvent() override { return &focus_event_; } - IEvent* MouseEnterLeaveEvent() override { - return &mouse_enter_leave_event_; - } - IEvent* MouseMoveEvent() override { return &mouse_move_event_; } - IEvent* MouseDownEvent() - override { - return &mouse_down_event_; - } - IEvent* MouseUpEvent() - override { - return &mouse_up_event_; - } - IEvent* KeyDownEvent() override { - return &key_down_event_; - } - IEvent* KeyUpEvent() override { - return &key_up_event_; - } - - IEvent* NativeMessageEvent() { - return &native_message_event_; - } - - IInputMethodContext* GetInputMethodContext() override; - - // Get the handle of the window. Return null if window is invalid. - HWND GetWindowHandle() const { return hwnd_; } - - bool HandleNativeWindowMessage(HWND hwnd, UINT msg, WPARAM w_param, - LPARAM l_param, LRESULT* result); - - graph::win::direct::D2DWindowRenderTarget* GetWindowRenderTarget() const { - return window_render_target_.get(); - } - - //*************** region: dpi *************** - float GetDpi() const { return dpi_; } - - inline int DipToPixel(const float dip) { - return static_cast(dip * GetDpi() / 96.0f); - } - - inline POINT DipToPixel(const Point& dip_point) { - POINT result; - result.x = DipToPixel(dip_point.x); - result.y = DipToPixel(dip_point.y); - return result; - } - - inline float PixelToDip(const int pixel) { - return static_cast(pixel) * 96.0f / GetDpi(); - } - - inline Point PixelToDip(const POINT& pi_point) { - return Point(PixelToDip(pi_point.x), PixelToDip(pi_point.y)); - } - - private: - // Get the client rect in pixel. - RECT GetClientRectPixel(); - - //*************** region: native messages *************** - - void OnDestroyInternal(); - void OnPaintInternal(); - void OnResizeInternal(int new_width, int new_height); - - void OnSetFocusInternal(); - void OnKillFocusInternal(); - - void OnMouseMoveInternal(POINT point); - void OnMouseLeaveInternal(); - void OnMouseDownInternal(platform::native::MouseButton button, POINT point); - void OnMouseUpInternal(platform::native::MouseButton button, POINT point); - - void OnMouseWheelInternal(short delta, POINT point); - void OnKeyDownInternal(int virtual_code); - void OnKeyUpInternal(int virtual_code); - - void OnActivatedInternal(); - void OnDeactivatedInternal(); - - private: - WinUiApplication* application_; - - // when delete is called first, it set this to true to indicate - // destroy message handler not to double delete this instance; - // when destroy handler is called first (by user action or method - // Close), it set this to true to indicate delete not call Close - // again. - bool sync_flag_ = false; - - HWND hwnd_; - WinNativeWindow* parent_window_; - - float dpi_; - - bool has_focus_ = false; - bool is_mouse_in_ = false; - - std::unique_ptr - window_render_target_; - - std::shared_ptr cursor_; - - std::unique_ptr input_method_context_; - - Event destroy_event_; - Event paint_event_; - Event resize_event_; - Event focus_event_; - Event mouse_enter_leave_event_; - Event mouse_move_event_; - Event mouse_down_event_; - Event mouse_up_event_; - Event key_down_event_; - Event key_up_event_; - - Event native_message_event_; -}; -} // namespace cru::platform::native::win diff --git a/include/cru/win/native/WindowClass.hpp b/include/cru/win/native/WindowClass.hpp deleted file mode 100644 index fdd55065..00000000 --- a/include/cru/win/native/WindowClass.hpp +++ /dev/null @@ -1,24 +0,0 @@ -#pragma once -#include "Base.hpp" - -#include - -namespace cru::platform::native::win { -class WindowClass : public Object { - public: - WindowClass(std::wstring name, WNDPROC window_proc, HINSTANCE h_instance); - - CRU_DELETE_COPY(WindowClass) - CRU_DELETE_MOVE(WindowClass) - - ~WindowClass() override = default; - - const wchar_t* GetName() const { return name_.c_str(); } - - ATOM GetAtom() const { return atom_; } - - private: - std::wstring name_; - ATOM atom_; -}; -} // namespace cru::platform::native::win diff --git a/include/cru/win/native/WindowNativeMessageEventArgs.hpp b/include/cru/win/native/WindowNativeMessageEventArgs.hpp deleted file mode 100644 index 84a7a123..00000000 --- a/include/cru/win/native/WindowNativeMessageEventArgs.hpp +++ /dev/null @@ -1,40 +0,0 @@ -#pragma once -#include "../WinPreConfig.hpp" - -#include "cru/common/Base.hpp" - -namespace cru::platform::native::win { -struct WindowNativeMessage { - HWND hwnd; - UINT msg; - WPARAM w_param; - LPARAM l_param; -}; - -class WindowNativeMessageEventArgs : public Object { - public: - WindowNativeMessageEventArgs(const WindowNativeMessage& message) - : message_(message) {} - CRU_DEFAULT_COPY(WindowNativeMessageEventArgs) - CRU_DEFAULT_MOVE(WindowNativeMessageEventArgs) - ~WindowNativeMessageEventArgs() override = default; - - const WindowNativeMessage& GetWindowMessage() const { return message_; } - - LRESULT GetResult() const { return result_; } - void SetResult(LRESULT result) { result_ = result; } - - bool IsHandled() const { return handled_; } - void SetHandled(bool handled) { handled_ = handled; } - - void HandleWithResult(LRESULT result) { - handled_ = true; - result_ = result; - } - - private: - WindowNativeMessage message_; - LRESULT result_; - bool handled_ = false; -}; -} // namespace cru::platform::native::win diff --git a/src/platform/CMakeLists.txt b/src/platform/CMakeLists.txt index 51253b56..623ec08f 100644 --- a/src/platform/CMakeLists.txt +++ b/src/platform/CMakeLists.txt @@ -10,5 +10,5 @@ target_sources(cru_platform_base INTERFACE ) target_link_libraries(cru_platform_base INTERFACE cru_base) -add_subdirectory(graph) -add_subdirectory(native) +add_subdirectory(graphics) +add_subdirectory(gui) diff --git a/src/platform/graph/CMakeLists.txt b/src/platform/graph/CMakeLists.txt deleted file mode 100644 index 3bf11e8d..00000000 --- a/src/platform/graph/CMakeLists.txt +++ /dev/null @@ -1,14 +0,0 @@ -set(CRU_PLATFORM_GRAPH_INCLUDE_DIR ${CRU_INCLUDE_DIR}/cru/platform/graph) -add_library(cru_platform_graph INTERFACE) -target_sources(cru_platform_graph INTERFACE - ${CRU_PLATFORM_GRAPH_INCLUDE_DIR}/Base.hpp - ${CRU_PLATFORM_GRAPH_INCLUDE_DIR}/Brush.hpp - ${CRU_PLATFORM_GRAPH_INCLUDE_DIR}/Font.hpp - ${CRU_PLATFORM_GRAPH_INCLUDE_DIR}/Geometry.hpp - ${CRU_PLATFORM_GRAPH_INCLUDE_DIR}/Factory.hpp - ${CRU_PLATFORM_GRAPH_INCLUDE_DIR}/Resource.hpp - ${CRU_PLATFORM_GRAPH_INCLUDE_DIR}/Painter.hpp - ${CRU_PLATFORM_GRAPH_INCLUDE_DIR}/TextLayout.hpp - ${CRU_PLATFORM_GRAPH_INCLUDE_DIR}/util/Painter.hpp -) -target_link_libraries(cru_platform_graph INTERFACE cru_platform_base) diff --git a/src/platform/graphics/CMakeLists.txt b/src/platform/graphics/CMakeLists.txt new file mode 100644 index 00000000..5f841267 --- /dev/null +++ b/src/platform/graphics/CMakeLists.txt @@ -0,0 +1,14 @@ +set(CRU_PLATFORM_GRAPHICS_INCLUDE_DIR ${CRU_INCLUDE_DIR}/cru/platform/graphics) +add_library(cru_platform_graphics INTERFACE) +target_sources(cru_platform_graphics INTERFACE + ${CRU_PLATFORM_GRAPHICS_INCLUDE_DIR}/Base.hpp + ${CRU_PLATFORM_GRAPHICS_INCLUDE_DIR}/Brush.hpp + ${CRU_PLATFORM_GRAPHICS_INCLUDE_DIR}/Font.hpp + ${CRU_PLATFORM_GRAPHICS_INCLUDE_DIR}/Geometry.hpp + ${CRU_PLATFORM_GRAPHICS_INCLUDE_DIR}/Factory.hpp + ${CRU_PLATFORM_GRAPHICS_INCLUDE_DIR}/Resource.hpp + ${CRU_PLATFORM_GRAPHICS_INCLUDE_DIR}/Painter.hpp + ${CRU_PLATFORM_GRAPHICS_INCLUDE_DIR}/TextLayout.hpp + ${CRU_PLATFORM_GRAPHICS_INCLUDE_DIR}/util/Painter.hpp +) +target_link_libraries(cru_platform_graphics INTERFACE cru_platform_base) diff --git a/src/platform/gui/CMakeLists.txt b/src/platform/gui/CMakeLists.txt new file mode 100644 index 00000000..aca7620c --- /dev/null +++ b/src/platform/gui/CMakeLists.txt @@ -0,0 +1,14 @@ +set(CRU_PLATFORM_GUI_INCLUDE_DIR ${CRU_INCLUDE_DIR}/cru/platform/gui) +add_library(cru_platform_gui STATIC + Keyboard.cpp + UiApplication.cpp +) +target_sources(cru_platform_gui PUBLIC + ${CRU_PLATFORM_GUI_INCLUDE_DIR}/Base.hpp + ${CRU_PLATFORM_GUI_INCLUDE_DIR}/Cursor.hpp + ${CRU_PLATFORM_GUI_INCLUDE_DIR}/InputMethod.hpp + ${CRU_PLATFORM_GUI_INCLUDE_DIR}/Keyboard.hpp + ${CRU_PLATFORM_GUI_INCLUDE_DIR}/Window.hpp + ${CRU_PLATFORM_GUI_INCLUDE_DIR}/UiApplication.hpp +) +target_link_libraries(cru_platform_gui PUBLIC cru_platform_graphics) diff --git a/src/platform/gui/Keyboard.cpp b/src/platform/gui/Keyboard.cpp new file mode 100644 index 00000000..24880e00 --- /dev/null +++ b/src/platform/gui/Keyboard.cpp @@ -0,0 +1,142 @@ +#include "cru/platform/gui/Keyboard.hpp" + +#include +#include +#include + +namespace cru::platform::gui { +constexpr std::array(KeyCode::NumPad9) + 1> + key_code_string_list{u"Unknown", + u"LeftButton", + u"MiddleButton", + u"RightButton", + u"Escape", + u"F1", + u"F2", + u"F3", + u"F4", + u"F5", + u"F6", + u"F7", + u"F8", + u"F9", + u"F10", + u"F11", + u"F12", + u"N0", + u"N1", + u"N2", + u"N3", + u"N4", + u"N5", + u"N6", + u"N7", + u"N8", + u"N9", + u"A", + u"B", + u"C", + u"D", + u"E", + u"F", + u"G", + u"H", + u"I", + u"J", + u"K", + u"L", + u"M", + u"N", + u"O", + u"P", + u"Q", + u"R", + u"S", + u"T", + u"U", + u"V", + u"W", + u"X", + u"Y", + u"Z", + u"GraveAccent", + u"Tab", + u"CapsLock", + u"LeftShift", + u"LeftCtrl", + u"LeftSuper", + u"LeftAlt", + u"Minus", + u"Equal", + u"Backspace", + u"LeftSquareBracket", + u"RightSquareBracket", + u"BackSlash", + u"Semicolon", + u"Quote", + u"Comma", + u"Period", + u"Slash", + u"RightShift", + u"RightCtrl", + u"RightSuper", + u"RightAlt", + u"Insert", + u"Delete", + u"Home", + u"End", + u"PageUp", + u"PageDown", + u"Up", + u"Left", + u"Down", + u"Right", + u"PrintScreen", + u"ScrollLock", + u"Pause", + u"NumPad0", + u"NumPad1", + u"NumPad2", + u"NumPad3", + u"NumPad4", + u"NumPad5", + u"NumPad6", + u"NumPad7", + u"NumPad8", + u"NumPad9"}; + +std::u16string_view ToString(KeyCode key_code) { + if (static_cast(key_code) < 0 || + static_cast(key_code) >= + static_cast(key_code_string_list.size())) + return u"UNKNOWN_KEYCODENAME"; + + return key_code_string_list[static_cast(key_code)]; +} + +std::u16string ToString(KeyModifier key_modifier, + std::u16string_view separator) { + std::vector list; + if (key_modifier & KeyModifiers::shift) { + list.push_back(u"Shift"); + } + + if (key_modifier & KeyModifiers::ctrl) { + list.push_back(u"Ctrl"); + } + + if (key_modifier & KeyModifiers::alt) { + list.push_back(u"Shift"); + } + + if (list.empty()) return u""; + std::u16string result = list.front(); + for (auto iter = list.cbegin() + 1; iter != list.cend(); ++iter) { + result += separator; + result += *iter; + } + + return result; +} +} // namespace cru::platform::gui diff --git a/src/platform/gui/UiApplication.cpp b/src/platform/gui/UiApplication.cpp new file mode 100644 index 00000000..f095361e --- /dev/null +++ b/src/platform/gui/UiApplication.cpp @@ -0,0 +1,15 @@ +#include "cru/platform/gui/UiApplication.hpp" + +namespace cru::platform::gui { +IUiApplication* IUiApplication::instance = nullptr; + +IUiApplication::IUiApplication() { + if (instance) { + throw std::runtime_error("An ui application has already been created."); + } + + instance = this; +} + +IUiApplication::~IUiApplication() { instance = nullptr; } +} // namespace cru::platform::gui diff --git a/src/platform/native/CMakeLists.txt b/src/platform/native/CMakeLists.txt deleted file mode 100644 index 3fe4370a..00000000 --- a/src/platform/native/CMakeLists.txt +++ /dev/null @@ -1,14 +0,0 @@ -set(CRU_PLATFORM_NATIVE_INCLUDE_DIR ${CRU_INCLUDE_DIR}/cru/platform/native) -add_library(cru_platform_native STATIC - Keyboard.cpp - UiApplication.cpp -) -target_sources(cru_platform_native PUBLIC - ${CRU_PLATFORM_NATIVE_INCLUDE_DIR}/Base.hpp - ${CRU_PLATFORM_NATIVE_INCLUDE_DIR}/Cursor.hpp - ${CRU_PLATFORM_NATIVE_INCLUDE_DIR}/InputMethod.hpp - ${CRU_PLATFORM_NATIVE_INCLUDE_DIR}/Keyboard.hpp - ${CRU_PLATFORM_NATIVE_INCLUDE_DIR}/Window.hpp - ${CRU_PLATFORM_NATIVE_INCLUDE_DIR}/UiApplication.hpp -) -target_link_libraries(cru_platform_native PUBLIC cru_platform_graph) diff --git a/src/platform/native/Keyboard.cpp b/src/platform/native/Keyboard.cpp deleted file mode 100644 index dd0e8f23..00000000 --- a/src/platform/native/Keyboard.cpp +++ /dev/null @@ -1,142 +0,0 @@ -#include "cru/platform/native/Keyboard.hpp" - -#include -#include -#include - -namespace cru::platform::native { -constexpr std::array(KeyCode::NumPad9) + 1> - key_code_string_list{u"Unknown", - u"LeftButton", - u"MiddleButton", - u"RightButton", - u"Escape", - u"F1", - u"F2", - u"F3", - u"F4", - u"F5", - u"F6", - u"F7", - u"F8", - u"F9", - u"F10", - u"F11", - u"F12", - u"N0", - u"N1", - u"N2", - u"N3", - u"N4", - u"N5", - u"N6", - u"N7", - u"N8", - u"N9", - u"A", - u"B", - u"C", - u"D", - u"E", - u"F", - u"G", - u"H", - u"I", - u"J", - u"K", - u"L", - u"M", - u"N", - u"O", - u"P", - u"Q", - u"R", - u"S", - u"T", - u"U", - u"V", - u"W", - u"X", - u"Y", - u"Z", - u"GraveAccent", - u"Tab", - u"CapsLock", - u"LeftShift", - u"LeftCtrl", - u"LeftSuper", - u"LeftAlt", - u"Minus", - u"Equal", - u"Backspace", - u"LeftSquareBracket", - u"RightSquareBracket", - u"BackSlash", - u"Semicolon", - u"Quote", - u"Comma", - u"Period", - u"Slash", - u"RightShift", - u"RightCtrl", - u"RightSuper", - u"RightAlt", - u"Insert", - u"Delete", - u"Home", - u"End", - u"PageUp", - u"PageDown", - u"Up", - u"Left", - u"Down", - u"Right", - u"PrintScreen", - u"ScrollLock", - u"Pause", - u"NumPad0", - u"NumPad1", - u"NumPad2", - u"NumPad3", - u"NumPad4", - u"NumPad5", - u"NumPad6", - u"NumPad7", - u"NumPad8", - u"NumPad9"}; - -std::u16string_view ToString(KeyCode key_code) { - if (static_cast(key_code) < 0 || - static_cast(key_code) >= - static_cast(key_code_string_list.size())) - return u"UNKNOWN_KEYCODENAME"; - - return key_code_string_list[static_cast(key_code)]; -} - -std::u16string ToString(KeyModifier key_modifier, - std::u16string_view separator) { - std::vector list; - if (key_modifier & KeyModifiers::shift) { - list.push_back(u"Shift"); - } - - if (key_modifier & KeyModifiers::ctrl) { - list.push_back(u"Ctrl"); - } - - if (key_modifier & KeyModifiers::alt) { - list.push_back(u"Shift"); - } - - if (list.empty()) return u""; - std::u16string result = list.front(); - for (auto iter = list.cbegin() + 1; iter != list.cend(); ++iter) { - result += separator; - result += *iter; - } - - return result; -} -} // namespace cru::platform::native diff --git a/src/platform/native/UiApplication.cpp b/src/platform/native/UiApplication.cpp deleted file mode 100644 index 200b10e0..00000000 --- a/src/platform/native/UiApplication.cpp +++ /dev/null @@ -1,15 +0,0 @@ -#include "cru/platform/native/UiApplication.hpp" - -namespace cru::platform::native { -IUiApplication* IUiApplication::instance = nullptr; - -IUiApplication::IUiApplication() { - if (instance) { - throw std::runtime_error("An ui application has already been created."); - } - - instance = this; -} - -IUiApplication::~IUiApplication() { instance = nullptr; } -} // namespace cru::platform::native diff --git a/src/ui/CMakeLists.txt b/src/ui/CMakeLists.txt index 045fea24..45f64c88 100644 --- a/src/ui/CMakeLists.txt +++ b/src/ui/CMakeLists.txt @@ -63,4 +63,4 @@ target_sources(cru_ui PUBLIC ${CRU_UI_INCLUDE_DIR}/render/StackLayoutRenderObject.hpp ${CRU_UI_INCLUDE_DIR}/render/TextRenderObject.hpp ) -target_link_libraries(cru_ui PUBLIC cru_platform_native) +target_link_libraries(cru_ui PUBLIC cru_platform_gui) diff --git a/src/ui/Control.cpp b/src/ui/Control.cpp index 13b1c780..cae48c66 100644 --- a/src/ui/Control.cpp +++ b/src/ui/Control.cpp @@ -2,8 +2,8 @@ #include "RoutedEventDispatch.hpp" #include "cru/common/Base.hpp" -#include "cru/platform/native/Cursor.hpp" -#include "cru/platform/native/UiApplication.hpp" +#include "cru/platform/gui/Cursor.hpp" +#include "cru/platform/gui/UiApplication.hpp" #include "cru/ui/Base.hpp" #include "cru/ui/WindowHost.hpp" #include "cru/ui/render/RenderObject.hpp" @@ -11,9 +11,9 @@ #include namespace cru::ui { -using platform::native::ICursor; -using platform::native::IUiApplication; -using platform::native::SystemCursorType; +using platform::gui::ICursor; +using platform::gui::IUiApplication; +using platform::gui::SystemCursorType; Control::Control() { MouseEnterEvent()->Direct()->AddHandler([this](event::MouseEventArgs&) { diff --git a/src/ui/Helper.cpp b/src/ui/Helper.cpp index 6f67e701..88ead993 100644 --- a/src/ui/Helper.cpp +++ b/src/ui/Helper.cpp @@ -1,11 +1,11 @@ #include "Helper.hpp" -#include "cru/platform/graph/Factory.hpp" -#include "cru/platform/native/UiApplication.hpp" +#include "cru/platform/graphics/Factory.hpp" +#include "cru/platform/gui/UiApplication.hpp" namespace cru::ui { -using cru::platform::graph::IGraphFactory; -using cru::platform::native::IUiApplication; +using cru::platform::graphics::IGraphFactory; +using cru::platform::gui::IUiApplication; IGraphFactory* GetGraphFactory() { return IUiApplication::GetInstance()->GetGraphFactory(); diff --git a/src/ui/Helper.hpp b/src/ui/Helper.hpp index 6923852f..327f91ff 100644 --- a/src/ui/Helper.hpp +++ b/src/ui/Helper.hpp @@ -12,6 +12,6 @@ struct IUiApplication; } // namespace cru::platform namespace cru::ui { -cru::platform::graph::IGraphFactory* GetGraphFactory(); -cru::platform::native::IUiApplication* GetUiApplication(); +cru::platform::graphics::IGraphFactory* GetGraphFactory(); +cru::platform::gui::IUiApplication* GetUiApplication(); } // namespace cru::ui diff --git a/src/ui/UiManager.cpp b/src/ui/UiManager.cpp index 8a2029b9..62995f86 100644 --- a/src/ui/UiManager.cpp +++ b/src/ui/UiManager.cpp @@ -1,13 +1,13 @@ #include "cru/ui/UiManager.hpp" #include "Helper.hpp" -#include "cru/platform/graph/Brush.hpp" -#include "cru/platform/graph/Factory.hpp" -#include "cru/platform/graph/Font.hpp" -#include "cru/platform/native/UiApplication.hpp" +#include "cru/platform/graphics/Brush.hpp" +#include "cru/platform/graphics/Factory.hpp" +#include "cru/platform/graphics/Font.hpp" +#include "cru/platform/gui/UiApplication.hpp" namespace cru::ui { -using namespace cru::platform::graph; +using namespace cru::platform::graphics; namespace { std::unique_ptr CreateSolidColorBrush(IGraphFactory* factory, @@ -35,7 +35,7 @@ UiManager::UiManager() { theme_resource_.default_font = factory->CreateFont(theme_resource_.default_font_family, 24.0f); - const auto black_brush = std::shared_ptr( + const auto black_brush = std::shared_ptr( CreateSolidColorBrush(factory, colors::black)); theme_resource_.text_brush = black_brush; theme_resource_.text_selection_brush = diff --git a/src/ui/WindowHost.cpp b/src/ui/WindowHost.cpp index 8c61d27d..4b32467b 100644 --- a/src/ui/WindowHost.cpp +++ b/src/ui/WindowHost.cpp @@ -2,10 +2,10 @@ #include "RoutedEventDispatch.hpp" #include "cru/common/Logger.hpp" -#include "cru/platform/graph/Painter.hpp" -#include "cru/platform/native/InputMethod.hpp" -#include "cru/platform/native/UiApplication.hpp" -#include "cru/platform/native/Window.hpp" +#include "cru/platform/graphics/Painter.hpp" +#include "cru/platform/gui/InputMethod.hpp" +#include "cru/platform/gui/UiApplication.hpp" +#include "cru/platform/gui/Window.hpp" #include "cru/ui/DebugFlags.hpp" #include "cru/ui/Window.hpp" #include "cru/ui/render/MeasureRequirement.hpp" @@ -14,8 +14,8 @@ #include namespace cru::ui { -using platform::native::INativeWindow; -using platform::native::IUiApplication; +using platform::gui::INativeWindow; +using platform::gui::IUiApplication; namespace event_names { #ifdef CRU_DEBUG @@ -149,7 +149,7 @@ void WindowHost::InvalidateLayout() { if constexpr (debug_flags::layout) log::TagDebug(log_tag, u"A relayout is requested."); if (!need_layout_) { - platform::native::IUiApplication::GetInstance()->SetImmediate([this] { + platform::gui::IUiApplication::GetInstance()->SetImmediate([this] { Relayout(); need_layout_ = false; InvalidatePaint(); @@ -272,10 +272,10 @@ void WindowHost::OnNativeResize(INativeWindow* window, const Size& size) { } void WindowHost::OnNativeFocus(INativeWindow* window, - platform::native::FocusChangeType focus) { + platform::gui::FocusChangeType focus) { CRU_UNUSED(window) - focus == platform::native::FocusChangeType::Gain + focus == platform::gui::FocusChangeType::Gain ? DispatchEvent(event_names::GainFocus, focus_control_, &Control::GainFocusEvent, nullptr, true) : DispatchEvent(event_names::LoseFocus, focus_control_, @@ -283,10 +283,10 @@ void WindowHost::OnNativeFocus(INativeWindow* window, } void WindowHost::OnNativeMouseEnterLeave( - INativeWindow* window, platform::native::MouseEnterLeaveType type) { + INativeWindow* window, platform::gui::MouseEnterLeaveType type) { CRU_UNUSED(window) - if (type == platform::native::MouseEnterLeaveType::Leave) { + if (type == platform::gui::MouseEnterLeaveType::Leave) { DispatchEvent(event_names::MouseLeave, mouse_hover_control_, &Control::MouseLeaveEvent, nullptr); mouse_hover_control_ = nullptr; @@ -328,7 +328,7 @@ void WindowHost::OnNativeMouseMove(INativeWindow* window, const Point& point) { void WindowHost::OnNativeMouseDown( INativeWindow* window, - const platform::native::NativeMouseButtonEventArgs& args) { + const platform::gui::NativeMouseButtonEventArgs& args) { CRU_UNUSED(window) Control* control = @@ -339,7 +339,7 @@ void WindowHost::OnNativeMouseDown( void WindowHost::OnNativeMouseUp( INativeWindow* window, - const platform::native::NativeMouseButtonEventArgs& args) { + const platform::gui::NativeMouseButtonEventArgs& args) { CRU_UNUSED(window) Control* control = @@ -349,7 +349,7 @@ void WindowHost::OnNativeMouseUp( } void WindowHost::OnNativeKeyDown( - INativeWindow* window, const platform::native::NativeKeyEventArgs& args) { + INativeWindow* window, const platform::gui::NativeKeyEventArgs& args) { CRU_UNUSED(window) DispatchEvent(event_names::KeyDown, focus_control_, &Control::KeyDownEvent, @@ -357,7 +357,7 @@ void WindowHost::OnNativeKeyDown( } void WindowHost::OnNativeKeyUp( - INativeWindow* window, const platform::native::NativeKeyEventArgs& args) { + INativeWindow* window, const platform::gui::NativeKeyEventArgs& args) { CRU_UNUSED(window) DispatchEvent(event_names::KeyUp, focus_control_, &Control::KeyUpEvent, diff --git a/src/ui/controls/Button.cpp b/src/ui/controls/Button.cpp index 6f6af878..5f7ed143 100644 --- a/src/ui/controls/Button.cpp +++ b/src/ui/controls/Button.cpp @@ -2,15 +2,15 @@ #include #include "../Helper.hpp" -#include "cru/platform/graph/Brush.hpp" -#include "cru/platform/native/Cursor.hpp" -#include "cru/platform/native/UiApplication.hpp" +#include "cru/platform/graphics/Brush.hpp" +#include "cru/platform/gui/Cursor.hpp" +#include "cru/platform/gui/UiApplication.hpp" #include "cru/ui/render/BorderRenderObject.hpp" #include "cru/ui/UiManager.hpp" #include "cru/ui/Window.hpp" namespace cru::ui::controls { -using cru::platform::native::SystemCursorType; +using cru::platform::gui::SystemCursorType; namespace { void Set(render::BorderRenderObject* o, const ButtonStateStyle& s) { @@ -21,7 +21,7 @@ void Set(render::BorderRenderObject* o, const ButtonStateStyle& s) { o->SetBackgroundBrush(s.background_brush); } -std::shared_ptr GetSystemCursor( +std::shared_ptr GetSystemCursor( SystemCursorType type) { return GetUiApplication()->GetCursorManager()->GetSystemCursor(type); } diff --git a/src/ui/controls/Container.cpp b/src/ui/controls/Container.cpp index de58ee64..8b15c566 100644 --- a/src/ui/controls/Container.cpp +++ b/src/ui/controls/Container.cpp @@ -1,6 +1,6 @@ #include "cru/ui/controls/Container.hpp" -#include "cru/platform/graph/Factory.hpp" +#include "cru/platform/graphics/Factory.hpp" #include "cru/ui/render/BorderRenderObject.hpp" namespace cru::ui::controls { diff --git a/src/ui/controls/TextControlService.hpp b/src/ui/controls/TextControlService.hpp index 3c082bad..8ad87416 100644 --- a/src/ui/controls/TextControlService.hpp +++ b/src/ui/controls/TextControlService.hpp @@ -2,11 +2,11 @@ #include "../Helper.hpp" #include "cru/common/Logger.hpp" #include "cru/common/StringUtil.hpp" -#include "cru/platform/graph/Font.hpp" -#include "cru/platform/graph/Painter.hpp" -#include "cru/platform/native/InputMethod.hpp" -#include "cru/platform/native/UiApplication.hpp" -#include "cru/platform/native/Window.hpp" +#include "cru/platform/graphics/Font.hpp" +#include "cru/platform/graphics/Painter.hpp" +#include "cru/platform/gui/InputMethod.hpp" +#include "cru/platform/gui/UiApplication.hpp" +#include "cru/platform/gui/Window.hpp" #include "cru/ui/Base.hpp" #include "cru/ui/Control.hpp" #include "cru/ui/DebugFlags.hpp" @@ -135,10 +135,10 @@ class TextControlService : public Object { this->SyncTextRenderObject(); } - platform::native::IInputMethodContext* GetInputMethodContext() { + platform::gui::IInputMethodContext* GetInputMethodContext() { WindowHost* host = this->control_->GetWindowHost(); if (!host) return nullptr; - platform::native::INativeWindow* native_window = host->GetNativeWindow(); + platform::gui::INativeWindow* native_window = host->GetNativeWindow(); if (!native_window) return nullptr; return native_window->GetInputMethodContext(); } @@ -149,7 +149,7 @@ class TextControlService : public Object { input_method_context->CancelComposition(); } - std::optional GetCompositionInfo() { + std::optional GetCompositionInfo() { auto input_method_context = GetInputMethodContext(); if (input_method_context == nullptr) return std::nullopt; auto composition_info = input_method_context->GetCompositionText(); @@ -360,8 +360,8 @@ class TextControlService : public Object { void KeyDownHandler(event::KeyEventArgs& args) { const auto key_code = args.GetKeyCode(); - using cru::platform::native::KeyCode; - using cru::platform::native::KeyModifiers; + using cru::platform::gui::KeyCode; + using cru::platform::gui::KeyModifiers; switch (key_code) { case KeyCode::Backspace: { @@ -469,7 +469,7 @@ class TextControlService : public Object { bool editable_ = false; bool caret_visible_ = false; - platform::native::TimerAutoCanceler caret_timer_canceler_; + platform::gui::TimerAutoCanceler caret_timer_canceler_; int caret_blink_duration_ = k_default_caret_blink_duration; ShortcutHub shortcut_hub_; diff --git a/src/ui/render/BorderRenderObject.cpp b/src/ui/render/BorderRenderObject.cpp index b7e1e709..8e16d8cb 100644 --- a/src/ui/render/BorderRenderObject.cpp +++ b/src/ui/render/BorderRenderObject.cpp @@ -2,9 +2,9 @@ #include "../Helper.hpp" #include "cru/common/Logger.hpp" -#include "cru/platform/graph/Factory.hpp" -#include "cru/platform/graph/Geometry.hpp" -#include "cru/platform/graph/util/Painter.hpp" +#include "cru/platform/graphics/Factory.hpp" +#include "cru/platform/graphics/Geometry.hpp" +#include "cru/platform/graphics/util/Painter.hpp" #include @@ -51,7 +51,7 @@ RenderObject* BorderRenderObject::HitTest(const Point& point) { } } -void BorderRenderObject::OnDrawCore(platform::graph::IPainter* painter) { +void BorderRenderObject::OnDrawCore(platform::graphics::IPainter* painter) { if (background_brush_ != nullptr) painter->FillGeometry(border_inner_geometry_.get(), background_brush_.get()); @@ -235,7 +235,7 @@ void BorderRenderObject::RecreateGeometry() { r.left_bottom - Point{t.left, t.bottom}, r.right_bottom - Point{t.right, t.bottom}); - auto f = [](platform::graph::IGeometryBuilder* builder, const Rect& rect, + auto f = [](platform::graphics::IGeometryBuilder* builder, const Rect& rect, const CornerRadius& corner) { builder->BeginFigure(Point(rect.left + corner.left_top.x, rect.top)); builder->LineTo(Point(rect.GetRight() - corner.right_top.x, rect.top)); @@ -263,7 +263,7 @@ void BorderRenderObject::RecreateGeometry() { size.width - margin.GetHorizontalTotal(), size.height - margin.GetVerticalTotal()}; const auto graph_factory = GetGraphFactory(); - std::unique_ptr builder{ + std::unique_ptr builder{ graph_factory->CreateGeometryBuilder()}; f(builder.get(), outer_rect, outer_radius); border_outer_geometry_ = builder->Build(); diff --git a/src/ui/render/CanvasRenderObject.cpp b/src/ui/render/CanvasRenderObject.cpp index 967fdcec..bf1155e1 100644 --- a/src/ui/render/CanvasRenderObject.cpp +++ b/src/ui/render/CanvasRenderObject.cpp @@ -10,7 +10,7 @@ RenderObject* CanvasRenderObject::HitTest(const Point& point) { return padding_rect.IsPointInside(point) ? this : nullptr; } -void CanvasRenderObject::OnDrawContent(platform::graph::IPainter* painter) { +void CanvasRenderObject::OnDrawContent(platform::graphics::IPainter* painter) { const auto rect = GetContentRect(); CanvasPaintEventArgs args{painter, rect.GetSize()}; paint_event_.Raise(args); diff --git a/src/ui/render/FlexLayoutRenderObject.cpp b/src/ui/render/FlexLayoutRenderObject.cpp index 36a2dcea..b1ef69ee 100644 --- a/src/ui/render/FlexLayoutRenderObject.cpp +++ b/src/ui/render/FlexLayoutRenderObject.cpp @@ -1,7 +1,7 @@ #include "cru/ui/render/FlexLayoutRenderObject.hpp" #include "cru/common/Logger.hpp" -#include "cru/platform/graph/util/Painter.hpp" +#include "cru/platform/graphics/util/Painter.hpp" #include "cru/ui/render/LayoutHelper.hpp" #include diff --git a/src/ui/render/RenderObject.cpp b/src/ui/render/RenderObject.cpp index 57929a21..09410113 100644 --- a/src/ui/render/RenderObject.cpp +++ b/src/ui/render/RenderObject.cpp @@ -1,7 +1,7 @@ #include "cru/ui/render/RenderObject.hpp" #include "cru/common/Logger.hpp" -#include "cru/platform/graph/util/Painter.hpp" +#include "cru/platform/graphics/util/Painter.hpp" #include "cru/ui/DebugFlags.hpp" #include "cru/ui/WindowHost.hpp" @@ -103,7 +103,7 @@ void RenderObject::Layout(const Point& offset) { OnLayoutCore(); } -void RenderObject::Draw(platform::graph::IPainter* painter) { +void RenderObject::Draw(platform::graphics::IPainter* painter) { OnDrawCore(painter); } @@ -138,29 +138,29 @@ void RenderObject::OnRemoveChild(RenderObject* removed_child, Index position) { InvalidatePaint(); } -void RenderObject::DefaultDrawChildren(platform::graph::IPainter* painter) { +void RenderObject::DefaultDrawChildren(platform::graphics::IPainter* painter) { for (const auto child : GetChildren()) { auto offset = child->GetOffset(); - platform::graph::util::WithTransform( + platform::graphics::util::WithTransform( painter, platform::Matrix::Translation(offset.x, offset.y), [child](auto p) { child->Draw(p); }); } } -void RenderObject::DefaultDrawContent(platform::graph::IPainter* painter) { +void RenderObject::DefaultDrawContent(platform::graphics::IPainter* painter) { const auto content_rect = GetContentRect(); - platform::graph::util::WithTransform( + platform::graphics::util::WithTransform( painter, Matrix::Translation(content_rect.left, content_rect.top), [this](auto p) { this->OnDrawContent(p); }); } -void RenderObject::OnDrawCore(platform::graph::IPainter* painter) { +void RenderObject::OnDrawCore(platform::graphics::IPainter* painter) { DefaultDrawContent(painter); DefaultDrawChildren(painter); } -void RenderObject::OnDrawContent(platform::graph::IPainter* painter) { +void RenderObject::OnDrawContent(platform::graphics::IPainter* painter) { CRU_UNUSED(painter); } diff --git a/src/ui/render/ScrollRenderObject.cpp b/src/ui/render/ScrollRenderObject.cpp index 24ea351a..e621cd0c 100644 --- a/src/ui/render/ScrollRenderObject.cpp +++ b/src/ui/render/ScrollRenderObject.cpp @@ -1,7 +1,7 @@ #include "cru/ui/render/ScrollRenderObject.hpp" -#include "cru/platform/graph/Painter.hpp" -#include "cru/platform/graph/util/Painter.hpp" +#include "cru/platform/graphics/Painter.hpp" +#include "cru/platform/graphics/util/Painter.hpp" #include @@ -42,14 +42,14 @@ RenderObject* ScrollRenderObject::HitTest(const Point& point) { return rect.IsPointInside(point) ? this : nullptr; } // namespace cru::ui::render -void ScrollRenderObject::OnDrawCore(platform::graph::IPainter* painter) { +void ScrollRenderObject::OnDrawCore(platform::graphics::IPainter* painter) { DefaultDrawContent(painter); if (const auto child = GetSingleChild()) { painter->PushLayer(this->GetPaddingRect()); const auto offset = child->GetOffset(); - platform::graph::util::WithTransform( + platform::graphics::util::WithTransform( painter, Matrix::Translation(offset.x, offset.y), - [child](platform::graph::IPainter* p) { child->Draw(p); }); + [child](platform::graphics::IPainter* p) { child->Draw(p); }); painter->PopLayer(); } } diff --git a/src/ui/render/TextRenderObject.cpp b/src/ui/render/TextRenderObject.cpp index 466c5084..9faab622 100644 --- a/src/ui/render/TextRenderObject.cpp +++ b/src/ui/render/TextRenderObject.cpp @@ -2,19 +2,19 @@ #include "../Helper.hpp" #include "cru/common/Logger.hpp" -#include "cru/platform/graph/Factory.hpp" -#include "cru/platform/graph/TextLayout.hpp" -#include "cru/platform/graph/util/Painter.hpp" +#include "cru/platform/graphics/Factory.hpp" +#include "cru/platform/graphics/TextLayout.hpp" +#include "cru/platform/graphics/util/Painter.hpp" #include #include namespace cru::ui::render { TextRenderObject::TextRenderObject( - std::shared_ptr brush, - std::shared_ptr font, - std::shared_ptr selection_brush, - std::shared_ptr caret_brush) { + std::shared_ptr brush, + std::shared_ptr font, + std::shared_ptr selection_brush, + std::shared_ptr caret_brush) { Expects(brush); Expects(font); Expects(selection_brush); @@ -47,17 +47,17 @@ void TextRenderObject::SetText(std::u16string new_text) { } void TextRenderObject::SetBrush( - std::shared_ptr new_brush) { + std::shared_ptr new_brush) { Expects(new_brush); new_brush.swap(brush_); InvalidatePaint(); } -std::shared_ptr TextRenderObject::GetFont() const { +std::shared_ptr TextRenderObject::GetFont() const { return text_layout_->GetFont(); } -void TextRenderObject::SetFont(std::shared_ptr font) { +void TextRenderObject::SetFont(std::shared_ptr font) { Expects(font); text_layout_->SetFont(std::move(font)); } @@ -70,7 +70,7 @@ Point TextRenderObject::TextSinglePoint(gsl::index position, bool trailing) { return text_layout_->TextSinglePoint(position, trailing); } -platform::graph::TextHitTestResult TextRenderObject::TextHitTest( +platform::graphics::TextHitTestResult TextRenderObject::TextHitTest( const Point& point) { return text_layout_->HitTest(point); } @@ -81,7 +81,7 @@ void TextRenderObject::SetSelectionRange(std::optional new_range) { } void TextRenderObject::SetSelectionBrush( - std::shared_ptr new_brush) { + std::shared_ptr new_brush) { Expects(new_brush); new_brush.swap(selection_brush_); if (selection_range_ && selection_range_->count) { @@ -106,7 +106,7 @@ void TextRenderObject::SetCaretPosition(gsl::index position) { } void TextRenderObject::GetCaretBrush( - std::shared_ptr brush) { + std::shared_ptr brush) { Expects(brush); brush.swap(caret_brush_); if (draw_caret_) { @@ -159,7 +159,7 @@ RenderObject* TextRenderObject::HitTest(const Point& point) { return padding_rect.IsPointInside(point) ? this : nullptr; } -void TextRenderObject::OnDrawContent(platform::graph::IPainter* painter) { +void TextRenderObject::OnDrawContent(platform::graphics::IPainter* painter) { if (this->selection_range_.has_value()) { const auto&& rects = text_layout_->TextRangeRect(this->selection_range_.value()); diff --git a/src/win/CMakeLists.txt b/src/win/CMakeLists.txt index 06f947a1..bf8de863 100644 --- a/src/win/CMakeLists.txt +++ b/src/win/CMakeLists.txt @@ -14,5 +14,5 @@ target_sources(cru_win_base PUBLIC target_compile_definitions(cru_win_base PUBLIC UNICODE _UNICODE) # use unicode target_link_libraries(cru_win_base PUBLIC cru_base) -add_subdirectory(graph) -add_subdirectory(native) +add_subdirectory(graphics) +add_subdirectory(gui) diff --git a/src/win/graph/CMakeLists.txt b/src/win/graph/CMakeLists.txt deleted file mode 100644 index c90537ac..00000000 --- a/src/win/graph/CMakeLists.txt +++ /dev/null @@ -1 +0,0 @@ -add_subdirectory(direct) diff --git a/src/win/graph/direct/Brush.cpp b/src/win/graph/direct/Brush.cpp deleted file mode 100644 index 2b9d4ac3..00000000 --- a/src/win/graph/direct/Brush.cpp +++ /dev/null @@ -1,17 +0,0 @@ -#include "cru/win/graph/direct/Brush.hpp" - -#include "cru/win/graph/direct/ConvertUtil.hpp" -#include "cru/win/graph/direct/Exception.hpp" -#include "cru/win/graph/direct/Factory.hpp" - -namespace cru::platform::graph::win::direct { -D2DSolidColorBrush::D2DSolidColorBrush(DirectGraphFactory* factory) - : DirectGraphResource(factory) { - ThrowIfFailed(factory->GetDefaultD2D1DeviceContext()->CreateSolidColorBrush( - Convert(color_), &brush_)); -} - -void D2DSolidColorBrush::SetColor(const Color& color) { - brush_->SetColor(Convert(color)); -} -} // namespace cru::platform::graph::win::direct diff --git a/src/win/graph/direct/CMakeLists.txt b/src/win/graph/direct/CMakeLists.txt deleted file mode 100644 index 070b7b51..00000000 --- a/src/win/graph/direct/CMakeLists.txt +++ /dev/null @@ -1,29 +0,0 @@ -set(CRU_WIN_GRAPH_DIRECT_INCLUDE_DIR ${CRU_INCLUDE_DIR}/cru/win/graph/direct) - -add_library(cru_win_graph_direct STATIC - Brush.cpp - Font.cpp - Geometry.cpp - Factory.cpp - Painter.cpp - Resource.cpp - TextLayout.cpp - WindowPainter.cpp - WindowRenderTarget.cpp -) -target_sources(cru_win_graph_direct PUBLIC - ${CRU_WIN_GRAPH_DIRECT_INCLUDE_DIR}/Brush.hpp - ${CRU_WIN_GRAPH_DIRECT_INCLUDE_DIR}/ComResource.hpp - ${CRU_WIN_GRAPH_DIRECT_INCLUDE_DIR}/ConvertUtil.hpp - ${CRU_WIN_GRAPH_DIRECT_INCLUDE_DIR}/Exception.hpp - ${CRU_WIN_GRAPH_DIRECT_INCLUDE_DIR}/Font.hpp - ${CRU_WIN_GRAPH_DIRECT_INCLUDE_DIR}/Geometry.hpp - ${CRU_WIN_GRAPH_DIRECT_INCLUDE_DIR}/Factory.hpp - ${CRU_WIN_GRAPH_DIRECT_INCLUDE_DIR}/Painter.hpp - ${CRU_WIN_GRAPH_DIRECT_INCLUDE_DIR}/Resource.hpp - ${CRU_WIN_GRAPH_DIRECT_INCLUDE_DIR}/TextLayout.hpp - ${CRU_WIN_GRAPH_DIRECT_INCLUDE_DIR}/WindowPainter.hpp - ${CRU_WIN_GRAPH_DIRECT_INCLUDE_DIR}/WindowRenderTarget.hpp -) -target_link_libraries(cru_win_graph_direct PUBLIC D3D11 D2d1 DWrite) -target_link_libraries(cru_win_graph_direct PUBLIC cru_win_base cru_platform_graph) diff --git a/src/win/graph/direct/Factory.cpp b/src/win/graph/direct/Factory.cpp deleted file mode 100644 index 03e64e13..00000000 --- a/src/win/graph/direct/Factory.cpp +++ /dev/null @@ -1,107 +0,0 @@ -#include "cru/win/graph/direct/Factory.hpp" - -#include "cru/common/Logger.hpp" -#include "cru/win/graph/direct/Brush.hpp" -#include "cru/win/graph/direct/Exception.hpp" -#include "cru/win/graph/direct/Font.hpp" -#include "cru/win/graph/direct/Geometry.hpp" -#include "cru/win/graph/direct/TextLayout.hpp" - -#include -#include - -namespace cru::platform::graph::win::direct { -namespace { -void InitializeCom() { - const auto hresult = ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); - if (FAILED(hresult)) { - throw HResultError(hresult, "Failed to call CoInitializeEx."); - } - if (hresult == S_FALSE) { - log::Debug( - u"Try to call CoInitializeEx, but it seems COM is already " - u"initialized."); - } -} - -void UninitializeCom() { ::CoUninitialize(); } -} // namespace - -DirectGraphFactory::DirectGraphFactory() { - // TODO! Detect repeated creation. Because I don't think we can create two d2d - // and dwrite factory so we need to prevent the "probably dangerous" behavior. - - InitializeCom(); - - UINT creation_flags = D3D11_CREATE_DEVICE_BGRA_SUPPORT; - -#ifdef CRU_DEBUG - creation_flags |= D3D11_CREATE_DEVICE_DEBUG; -#endif - - const D3D_FEATURE_LEVEL feature_levels[] = { - D3D_FEATURE_LEVEL_11_1, D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1, - D3D_FEATURE_LEVEL_10_0, D3D_FEATURE_LEVEL_9_3, D3D_FEATURE_LEVEL_9_2, - D3D_FEATURE_LEVEL_9_1}; - - Microsoft::WRL::ComPtr d3d11_device_context; - - ThrowIfFailed(D3D11CreateDevice( - nullptr, D3D_DRIVER_TYPE_HARDWARE, nullptr, creation_flags, - feature_levels, ARRAYSIZE(feature_levels), D3D11_SDK_VERSION, - &d3d11_device_, nullptr, &d3d11_device_context)); - - Microsoft::WRL::ComPtr dxgi_device; - ThrowIfFailed(d3d11_device_->QueryInterface(dxgi_device.GetAddressOf())); - - ThrowIfFailed(D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, - IID_PPV_ARGS(&d2d1_factory_))); - - ThrowIfFailed(d2d1_factory_->CreateDevice(dxgi_device.Get(), &d2d1_device_)); - - d2d1_device_context_ = CreateD2D1DeviceContext(); - - // Identify the physical adapter (GPU or card) this device is runs on. - Microsoft::WRL::ComPtr dxgi_adapter; - ThrowIfFailed(dxgi_device->GetAdapter(&dxgi_adapter)); - - // Get the factory object that created the DXGI device. - ThrowIfFailed(dxgi_adapter->GetParent(IID_PPV_ARGS(&dxgi_factory_))); - - ThrowIfFailed(DWriteCreateFactory( - DWRITE_FACTORY_TYPE_SHARED, __uuidof(IDWriteFactory), - reinterpret_cast(dwrite_factory_.GetAddressOf()))); - - ThrowIfFailed(dwrite_factory_->GetSystemFontCollection( - &dwrite_system_font_collection_)); -} - -DirectGraphFactory::~DirectGraphFactory() { UninitializeCom(); } - -Microsoft::WRL::ComPtr -DirectGraphFactory::CreateD2D1DeviceContext() { - Microsoft::WRL::ComPtr d2d1_device_context; - ThrowIfFailed(d2d1_device_->CreateDeviceContext( - D2D1_DEVICE_CONTEXT_OPTIONS_NONE, &d2d1_device_context)); - return d2d1_device_context; -} - -std::unique_ptr DirectGraphFactory::CreateSolidColorBrush() { - return std::make_unique(this); -} - -std::unique_ptr DirectGraphFactory::CreateGeometryBuilder() { - return std::make_unique(this); -} - -std::unique_ptr DirectGraphFactory::CreateFont( - std::u16string font_family, float font_size) { - return std::make_unique(this, std::move(font_family), font_size); -} - -std::unique_ptr DirectGraphFactory::CreateTextLayout( - std::shared_ptr font, std::u16string text) { - return std::make_unique(this, std::move(font), - std::move(text)); -} -} // namespace cru::platform::graph::win::direct diff --git a/src/win/graph/direct/Font.cpp b/src/win/graph/direct/Font.cpp deleted file mode 100644 index 34de5b71..00000000 --- a/src/win/graph/direct/Font.cpp +++ /dev/null @@ -1,31 +0,0 @@ -#include "cru/win/graph/direct/Font.hpp" - -#include "cru/win/graph/direct/Exception.hpp" -#include "cru/win/graph/direct/Factory.hpp" - -#include -#include - -namespace cru::platform::graph::win::direct { -DWriteFont::DWriteFont(DirectGraphFactory* factory, std::u16string font_family, - float font_size) - : DirectGraphResource(factory), font_family_(std::move(font_family)) { - // Get locale - std::array buffer; - if (!::GetUserDefaultLocaleName(buffer.data(), - static_cast(buffer.size()))) - throw platform::win::Win32Error( - ::GetLastError(), "Failed to get locale when create dwrite font."); - - ThrowIfFailed(factory->GetDWriteFactory()->CreateTextFormat( - reinterpret_cast(font_family_.c_str()), nullptr, - DWRITE_FONT_WEIGHT_NORMAL, DWRITE_FONT_STYLE_NORMAL, - DWRITE_FONT_STRETCH_NORMAL, font_size, buffer.data(), &text_format_)); - - ThrowIfFailed(text_format_->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING)); - ThrowIfFailed( - text_format_->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR)); -} - -float DWriteFont::GetFontSize() { return text_format_->GetFontSize(); } -} // namespace cru::platform::graph::win::direct diff --git a/src/win/graph/direct/Geometry.cpp b/src/win/graph/direct/Geometry.cpp deleted file mode 100644 index e77b4749..00000000 --- a/src/win/graph/direct/Geometry.cpp +++ /dev/null @@ -1,62 +0,0 @@ -#include "cru/win/graph/direct/Geometry.hpp" - -#include "cru/win/graph/direct/ConvertUtil.hpp" -#include "cru/win/graph/direct/Exception.hpp" -#include "cru/win/graph/direct/Factory.hpp" - -namespace cru::platform::graph::win::direct { -D2DGeometryBuilder::D2DGeometryBuilder(DirectGraphFactory* factory) - : DirectGraphResource(factory) { - ThrowIfFailed(factory->GetD2D1Factory()->CreatePathGeometry(&geometry_)); - ThrowIfFailed(geometry_->Open(&geometry_sink_)); -} - -void D2DGeometryBuilder::CheckValidation() { - if (!IsValid()) - throw ReuseException("The geometry builder is already disposed."); -} - -void D2DGeometryBuilder::BeginFigure(const Point& point) { - CheckValidation(); - geometry_sink_->BeginFigure(Convert(point), D2D1_FIGURE_BEGIN_FILLED); -} - -void D2DGeometryBuilder::LineTo(const Point& point) { - CheckValidation(); - geometry_sink_->AddLine(Convert(point)); -} - -void D2DGeometryBuilder::QuadraticBezierTo(const Point& control_point, - const Point& end_point) { - CheckValidation(); - geometry_sink_->AddQuadraticBezier( - D2D1::QuadraticBezierSegment(Convert(control_point), Convert(end_point))); -} - -void D2DGeometryBuilder::CloseFigure(bool close) { - CheckValidation(); - geometry_sink_->EndFigure(close ? D2D1_FIGURE_END_CLOSED - : D2D1_FIGURE_END_OPEN); -} - -std::unique_ptr D2DGeometryBuilder::Build() { - CheckValidation(); - ThrowIfFailed(geometry_sink_->Close()); - geometry_sink_ = nullptr; - auto geometry = - std::make_unique(GetDirectFactory(), std::move(geometry_)); - geometry_ = nullptr; - return geometry; -} - -D2DGeometry::D2DGeometry(DirectGraphFactory* factory, - Microsoft::WRL::ComPtr geometry) - : DirectGraphResource(factory), geometry_(std::move(geometry)) {} - -bool D2DGeometry::FillContains(const Point& point) { - BOOL result; - ThrowIfFailed(geometry_->FillContainsPoint( - Convert(point), D2D1::Matrix3x2F::Identity(), &result)); - return result != 0; -} -} // namespace cru::platform::graph::win::direct diff --git a/src/win/graph/direct/Painter.cpp b/src/win/graph/direct/Painter.cpp deleted file mode 100644 index 3ffb5208..00000000 --- a/src/win/graph/direct/Painter.cpp +++ /dev/null @@ -1,104 +0,0 @@ -#include "cru/win/graph/direct/Painter.hpp" - -#include "cru/platform/Check.hpp" -#include "cru/win/graph/direct/Brush.hpp" -#include "cru/win/graph/direct/ConvertUtil.hpp" -#include "cru/win/graph/direct/Exception.hpp" -#include "cru/win/graph/direct/Geometry.hpp" -#include "cru/win/graph/direct/TextLayout.hpp" - -#include - -namespace cru::platform::graph::win::direct { -D2DPainter::D2DPainter(ID2D1RenderTarget* render_target) { - Expects(render_target); - render_target_ = render_target; -} - -platform::Matrix D2DPainter::GetTransform() { - CheckValidation(); - D2D1_MATRIX_3X2_F m; - render_target_->GetTransform(&m); - return Convert(m); -} - -void D2DPainter::SetTransform(const platform::Matrix& matrix) { - CheckValidation(); - render_target_->SetTransform(Convert(matrix)); -} - -void D2DPainter::Clear(const Color& color) { - CheckValidation(); - render_target_->Clear(Convert(color)); -} - -void D2DPainter::StrokeRectangle(const Rect& rectangle, IBrush* brush, - float width) { - CheckValidation(); - const auto b = CheckPlatform(brush, GetPlatformId()); - render_target_->DrawRectangle(Convert(rectangle), b->GetD2DBrushInterface(), - width); -} - -void D2DPainter::FillRectangle(const Rect& rectangle, IBrush* brush) { - CheckValidation(); - const auto b = CheckPlatform(brush, GetPlatformId()); - render_target_->FillRectangle(Convert(rectangle), b->GetD2DBrushInterface()); -} - -void D2DPainter::StrokeGeometry(IGeometry* geometry, IBrush* brush, - float width) { - CheckValidation(); - const auto g = CheckPlatform(geometry, GetPlatformId()); - const auto b = CheckPlatform(brush, GetPlatformId()); - render_target_->DrawGeometry(g->GetComInterface(), b->GetD2DBrushInterface(), - width); -} - -void D2DPainter::FillGeometry(IGeometry* geometry, IBrush* brush) { - CheckValidation(); - const auto g = CheckPlatform(geometry, GetPlatformId()); - const auto b = CheckPlatform(brush, GetPlatformId()); - render_target_->FillGeometry(g->GetComInterface(), b->GetD2DBrushInterface()); -} - -void D2DPainter::DrawText(const Point& offset, ITextLayout* text_layout, - IBrush* brush) { - CheckValidation(); - const auto t = CheckPlatform(text_layout, GetPlatformId()); - const auto b = CheckPlatform(brush, GetPlatformId()); - render_target_->DrawTextLayout(Convert(offset), t->GetComInterface(), - b->GetD2DBrushInterface()); -} - -void D2DPainter::PushLayer(const Rect& bounds) { - CheckValidation(); - - Microsoft::WRL::ComPtr layer; - ThrowIfFailed(render_target_->CreateLayer(&layer)); - - render_target_->PushLayer(D2D1::LayerParameters(Convert(bounds)), - layer.Get()); - - layers_.push_back(std::move(layer)); -} - -void D2DPainter::PopLayer() { - render_target_->PopLayer(); - layers_.pop_back(); -} - -void D2DPainter::EndDraw() { - if (is_drawing_) { - is_drawing_ = false; - DoEndDraw(); - } -} - -void D2DPainter::CheckValidation() { - if (!is_drawing_) { - throw cru::platform::ReuseException( - "Can't do that on painter after end drawing."); - } -} -} // namespace cru::platform::graph::win::direct diff --git a/src/win/graph/direct/Resource.cpp b/src/win/graph/direct/Resource.cpp deleted file mode 100644 index 772bb74b..00000000 --- a/src/win/graph/direct/Resource.cpp +++ /dev/null @@ -1,12 +0,0 @@ -#include "cru/win/graph/direct/Resource.hpp" - -#include "cru/win/graph/direct/Factory.hpp" - -namespace cru::platform::graph::win::direct { -DirectGraphResource::DirectGraphResource(DirectGraphFactory* factory) - : factory_(factory) { - Expects(factory); -} - -IGraphFactory* DirectGraphResource::GetGraphFactory() { return factory_; } -} // namespace cru::platform::graph::win::direct diff --git a/src/win/graph/direct/TextLayout.cpp b/src/win/graph/direct/TextLayout.cpp deleted file mode 100644 index 0d4a6392..00000000 --- a/src/win/graph/direct/TextLayout.cpp +++ /dev/null @@ -1,124 +0,0 @@ -#include "cru/win/graph/direct/TextLayout.hpp" - -#include "cru/common/Logger.hpp" -#include "cru/platform/Check.hpp" -#include "cru/win/graph/direct/Exception.hpp" -#include "cru/win/graph/direct/Factory.hpp" -#include "cru/win/graph/direct/Font.hpp" - -#include - -namespace cru::platform::graph::win::direct { -DWriteTextLayout::DWriteTextLayout(DirectGraphFactory* factory, - std::shared_ptr font, - std::u16string text) - : DirectGraphResource(factory), text_(std::move(text)) { - Expects(font); - font_ = CheckPlatform(font, GetPlatformId()); - - ThrowIfFailed(factory->GetDWriteFactory()->CreateTextLayout( - reinterpret_cast(text_.c_str()), - static_cast(text_.size()), font_->GetComInterface(), max_width_, - max_height_, &text_layout_)); -} - -DWriteTextLayout::~DWriteTextLayout() = default; - -std::u16string DWriteTextLayout::GetText() { return text_; } - -std::u16string_view DWriteTextLayout::GetTextView() { return text_; } - -void DWriteTextLayout::SetText(std::u16string new_text) { - text_.swap(new_text); - ThrowIfFailed(GetDirectFactory()->GetDWriteFactory()->CreateTextLayout( - reinterpret_cast(text_.c_str()), - static_cast(text_.size()), font_->GetComInterface(), max_width_, - max_height_, &text_layout_)); -} - -std::shared_ptr DWriteTextLayout::GetFont() { - return std::dynamic_pointer_cast(font_); -} - -void DWriteTextLayout::SetFont(std::shared_ptr font) { - font_ = CheckPlatform(font, GetPlatformId()); - ThrowIfFailed(GetDirectFactory()->GetDWriteFactory()->CreateTextLayout( - reinterpret_cast(text_.c_str()), - static_cast(text_.size()), font_->GetComInterface(), max_width_, - max_height_, &text_layout_)); -} - -void DWriteTextLayout::SetMaxWidth(float max_width) { - max_width_ = max_width; - ThrowIfFailed(text_layout_->SetMaxWidth(max_width_)); -} - -void DWriteTextLayout::SetMaxHeight(float max_height) { - max_height_ = max_height; - ThrowIfFailed(text_layout_->SetMaxHeight(max_height_)); -} - -Rect DWriteTextLayout::GetTextBounds() { - DWRITE_TEXT_METRICS metrics; - ThrowIfFailed(text_layout_->GetMetrics(&metrics)); - return Rect{metrics.left, metrics.top, metrics.width, metrics.height}; -} - -std::vector DWriteTextLayout::TextRangeRect( - const TextRange& text_range_arg) { - if (text_range_arg.count == 0) { - return {}; - } - const auto text_range = text_range_arg.Normalize(); - - DWRITE_TEXT_METRICS text_metrics; - ThrowIfFailed(text_layout_->GetMetrics(&text_metrics)); - const auto metrics_count = - text_metrics.lineCount * text_metrics.maxBidiReorderingDepth; - - std::vector hit_test_metrics(metrics_count); - UINT32 actual_count; - ThrowIfFailed(text_layout_->HitTestTextRange( - static_cast(text_range.position), - static_cast(text_range.count), 0, 0, hit_test_metrics.data(), - metrics_count, &actual_count)); - - hit_test_metrics.erase(hit_test_metrics.cbegin() + actual_count, - hit_test_metrics.cend()); - - std::vector result; - result.reserve(actual_count); - - for (const auto& metrics : hit_test_metrics) { - result.push_back( - Rect{metrics.left, metrics.top, metrics.width, metrics.height}); - } - - return result; -} - -Point DWriteTextLayout::TextSinglePoint(Index position, bool trailing) { - DWRITE_HIT_TEST_METRICS metrics; - FLOAT left; - FLOAT top; - ThrowIfFailed(text_layout_->HitTestTextPosition(static_cast(position), - static_cast(trailing), - &left, &top, &metrics)); - return Point{left, top}; -} - -TextHitTestResult DWriteTextLayout::HitTest(const Point& point) { - BOOL trailing; - BOOL inside; - DWRITE_HIT_TEST_METRICS metrics; - - ThrowIfFailed(text_layout_->HitTestPoint(point.x, point.y, &trailing, &inside, - &metrics)); - - TextHitTestResult result; - result.position = metrics.textPosition; - result.trailing = trailing != 0; - result.insideText = inside != 0; - return result; -} -} // namespace cru::platform::graph::win::direct diff --git a/src/win/graph/direct/WindowPainter.cpp b/src/win/graph/direct/WindowPainter.cpp deleted file mode 100644 index 74f7da7a..00000000 --- a/src/win/graph/direct/WindowPainter.cpp +++ /dev/null @@ -1,20 +0,0 @@ -#include "cru/win/graph/direct/WindowPainter.hpp" - -#include "cru/win/graph/direct/Exception.hpp" -#include "cru/win/graph/direct/Factory.hpp" -#include "cru/win/graph/direct/WindowRenderTarget.hpp" - -namespace cru::platform::graph::win::direct { -D2DWindowPainter::D2DWindowPainter(D2DWindowRenderTarget* render_target) - : D2DPainter(render_target->GetD2D1DeviceContext()), - render_target_(render_target) { - render_target_->GetD2D1DeviceContext()->BeginDraw(); -} - -D2DWindowPainter::~D2DWindowPainter() { EndDraw(); } - -void D2DWindowPainter::DoEndDraw() { - ThrowIfFailed(render_target_->GetD2D1DeviceContext()->EndDraw()); - render_target_->Present(); -} -} // namespace cru::platform::graph::win::direct diff --git a/src/win/graph/direct/WindowRenderTarget.cpp b/src/win/graph/direct/WindowRenderTarget.cpp deleted file mode 100644 index d26fccf6..00000000 --- a/src/win/graph/direct/WindowRenderTarget.cpp +++ /dev/null @@ -1,81 +0,0 @@ -#include "cru/win/graph/direct/WindowRenderTarget.hpp" - -#include "cru/win/graph/direct/Exception.hpp" -#include "cru/win/graph/direct/Factory.hpp" - -namespace cru::platform::graph::win::direct { -D2DWindowRenderTarget::D2DWindowRenderTarget( - gsl::not_null factory, HWND hwnd) - : factory_(factory), hwnd_(hwnd) { - const auto d3d11_device = factory->GetD3D11Device(); - const auto dxgi_factory = factory->GetDxgiFactory(); - - d2d1_device_context_ = factory->CreateD2D1DeviceContext(); - d2d1_device_context_->SetUnitMode(D2D1_UNIT_MODE_DIPS); - - // Allocate a descriptor. - DXGI_SWAP_CHAIN_DESC1 swap_chain_desc; - swap_chain_desc.Width = 0; // use automatic sizing - swap_chain_desc.Height = 0; - swap_chain_desc.Format = - DXGI_FORMAT_B8G8R8A8_UNORM; // this is the most common swapchain format - swap_chain_desc.Stereo = false; - swap_chain_desc.SampleDesc.Count = 1; // don't use multi-sampling - swap_chain_desc.SampleDesc.Quality = 0; - swap_chain_desc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; - swap_chain_desc.BufferCount = 2; // use double buffering to enable flip - swap_chain_desc.Scaling = DXGI_SCALING_NONE; - swap_chain_desc.SwapEffect = - DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL; // all apps must use this SwapEffect - swap_chain_desc.AlphaMode = DXGI_ALPHA_MODE_UNSPECIFIED; - swap_chain_desc.Flags = 0; - - // Get the final swap chain for this window from the DXGI factory. - ThrowIfFailed(dxgi_factory->CreateSwapChainForHwnd( - d3d11_device, hwnd, &swap_chain_desc, nullptr, nullptr, - &dxgi_swap_chain_)); - - CreateTargetBitmap(); -} - -void D2DWindowRenderTarget::SetDpi(float x, float y) { - d2d1_device_context_->SetDpi(x, y); -} - -void D2DWindowRenderTarget::ResizeBuffer(const int width, const int height) { - // In order to resize buffer, we need to untarget the buffer first. - d2d1_device_context_->SetTarget(nullptr); - target_bitmap_ = nullptr; - ThrowIfFailed(dxgi_swap_chain_->ResizeBuffers(0, width, height, - DXGI_FORMAT_UNKNOWN, 0)); - CreateTargetBitmap(); -} - -void D2DWindowRenderTarget::Present() { - ThrowIfFailed(dxgi_swap_chain_->Present(1, 0)); -} - -void D2DWindowRenderTarget::CreateTargetBitmap() { - Expects(target_bitmap_ == nullptr); // target bitmap must not exist. - - // Direct2D needs the dxgi version of the backbuffer surface pointer. - Microsoft::WRL::ComPtr dxgi_back_buffer; - ThrowIfFailed( - dxgi_swap_chain_->GetBuffer(0, IID_PPV_ARGS(&dxgi_back_buffer))); - - float dpi_x, dpi_y; - d2d1_device_context_->GetDpi(&dpi_x, &dpi_y); - - auto bitmap_properties = D2D1::BitmapProperties1( - D2D1_BITMAP_OPTIONS_TARGET | D2D1_BITMAP_OPTIONS_CANNOT_DRAW, - D2D1::PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_IGNORE), - dpi_x, dpi_y); - - // Get a D2D surface from the DXGI back buffer to use as the D2D render - // target. - ThrowIfFailed(d2d1_device_context_->CreateBitmapFromDxgiSurface( - dxgi_back_buffer.Get(), &bitmap_properties, &target_bitmap_)); - - d2d1_device_context_->SetTarget(target_bitmap_.Get()); -} -} // namespace cru::platform::graph::win::direct diff --git a/src/win/graphics/CMakeLists.txt b/src/win/graphics/CMakeLists.txt new file mode 100644 index 00000000..c90537ac --- /dev/null +++ b/src/win/graphics/CMakeLists.txt @@ -0,0 +1 @@ +add_subdirectory(direct) diff --git a/src/win/graphics/direct/Brush.cpp b/src/win/graphics/direct/Brush.cpp new file mode 100644 index 00000000..b7842b97 --- /dev/null +++ b/src/win/graphics/direct/Brush.cpp @@ -0,0 +1,17 @@ +#include "cru/win/graphics/direct/Brush.hpp" + +#include "cru/win/graphics/direct/ConvertUtil.hpp" +#include "cru/win/graphics/direct/Exception.hpp" +#include "cru/win/graphics/direct/Factory.hpp" + +namespace cru::platform::graphics::win::direct { +D2DSolidColorBrush::D2DSolidColorBrush(DirectGraphFactory* factory) + : DirectGraphResource(factory) { + ThrowIfFailed(factory->GetDefaultD2D1DeviceContext()->CreateSolidColorBrush( + Convert(color_), &brush_)); +} + +void D2DSolidColorBrush::SetColor(const Color& color) { + brush_->SetColor(Convert(color)); +} +} // namespace cru::platform::graphics::win::direct diff --git a/src/win/graphics/direct/CMakeLists.txt b/src/win/graphics/direct/CMakeLists.txt new file mode 100644 index 00000000..d4c96a65 --- /dev/null +++ b/src/win/graphics/direct/CMakeLists.txt @@ -0,0 +1,29 @@ +set(CRU_WIN_GRAPHICS_DIRECT_INCLUDE_DIR ${CRU_INCLUDE_DIR}/cru/win/graphics/direct) + +add_library(cru_win_graphics_direct STATIC + Brush.cpp + Font.cpp + Geometry.cpp + Factory.cpp + Painter.cpp + Resource.cpp + TextLayout.cpp + WindowPainter.cpp + WindowRenderTarget.cpp +) +target_sources(cru_win_graphics_direct PUBLIC + ${CRU_WIN_GRAPHICS_DIRECT_INCLUDE_DIR}/Brush.hpp + ${CRU_WIN_GRAPHICS_DIRECT_INCLUDE_DIR}/ComResource.hpp + ${CRU_WIN_GRAPHICS_DIRECT_INCLUDE_DIR}/ConvertUtil.hpp + ${CRU_WIN_GRAPHICS_DIRECT_INCLUDE_DIR}/Exception.hpp + ${CRU_WIN_GRAPHICS_DIRECT_INCLUDE_DIR}/Font.hpp + ${CRU_WIN_GRAPHICS_DIRECT_INCLUDE_DIR}/Geometry.hpp + ${CRU_WIN_GRAPHICS_DIRECT_INCLUDE_DIR}/Factory.hpp + ${CRU_WIN_GRAPHICS_DIRECT_INCLUDE_DIR}/Painter.hpp + ${CRU_WIN_GRAPHICS_DIRECT_INCLUDE_DIR}/Resource.hpp + ${CRU_WIN_GRAPHICS_DIRECT_INCLUDE_DIR}/TextLayout.hpp + ${CRU_WIN_GRAPHICS_DIRECT_INCLUDE_DIR}/WindowPainter.hpp + ${CRU_WIN_GRAPHICS_DIRECT_INCLUDE_DIR}/WindowRenderTarget.hpp +) +target_link_libraries(cru_win_graphics_direct PUBLIC D3D11 D2d1 DWrite) +target_link_libraries(cru_win_graphics_direct PUBLIC cru_win_base cru_platform_graphics) diff --git a/src/win/graphics/direct/Factory.cpp b/src/win/graphics/direct/Factory.cpp new file mode 100644 index 00000000..6694801f --- /dev/null +++ b/src/win/graphics/direct/Factory.cpp @@ -0,0 +1,107 @@ +#include "cru/win/graphics/direct/Factory.hpp" + +#include "cru/common/Logger.hpp" +#include "cru/win/graphics/direct/Brush.hpp" +#include "cru/win/graphics/direct/Exception.hpp" +#include "cru/win/graphics/direct/Font.hpp" +#include "cru/win/graphics/direct/Geometry.hpp" +#include "cru/win/graphics/direct/TextLayout.hpp" + +#include +#include + +namespace cru::platform::graphics::win::direct { +namespace { +void InitializeCom() { + const auto hresult = ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); + if (FAILED(hresult)) { + throw HResultError(hresult, "Failed to call CoInitializeEx."); + } + if (hresult == S_FALSE) { + log::Debug( + u"Try to call CoInitializeEx, but it seems COM is already " + u"initialized."); + } +} + +void UninitializeCom() { ::CoUninitialize(); } +} // namespace + +DirectGraphFactory::DirectGraphFactory() { + // TODO! Detect repeated creation. Because I don't think we can create two d2d + // and dwrite factory so we need to prevent the "probably dangerous" behavior. + + InitializeCom(); + + UINT creation_flags = D3D11_CREATE_DEVICE_BGRA_SUPPORT; + +#ifdef CRU_DEBUG + creation_flags |= D3D11_CREATE_DEVICE_DEBUG; +#endif + + const D3D_FEATURE_LEVEL feature_levels[] = { + D3D_FEATURE_LEVEL_11_1, D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1, + D3D_FEATURE_LEVEL_10_0, D3D_FEATURE_LEVEL_9_3, D3D_FEATURE_LEVEL_9_2, + D3D_FEATURE_LEVEL_9_1}; + + Microsoft::WRL::ComPtr d3d11_device_context; + + ThrowIfFailed(D3D11CreateDevice( + nullptr, D3D_DRIVER_TYPE_HARDWARE, nullptr, creation_flags, + feature_levels, ARRAYSIZE(feature_levels), D3D11_SDK_VERSION, + &d3d11_device_, nullptr, &d3d11_device_context)); + + Microsoft::WRL::ComPtr dxgi_device; + ThrowIfFailed(d3d11_device_->QueryInterface(dxgi_device.GetAddressOf())); + + ThrowIfFailed(D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, + IID_PPV_ARGS(&d2d1_factory_))); + + ThrowIfFailed(d2d1_factory_->CreateDevice(dxgi_device.Get(), &d2d1_device_)); + + d2d1_device_context_ = CreateD2D1DeviceContext(); + + // Identify the physical adapter (GPU or card) this device is runs on. + Microsoft::WRL::ComPtr dxgi_adapter; + ThrowIfFailed(dxgi_device->GetAdapter(&dxgi_adapter)); + + // Get the factory object that created the DXGI device. + ThrowIfFailed(dxgi_adapter->GetParent(IID_PPV_ARGS(&dxgi_factory_))); + + ThrowIfFailed(DWriteCreateFactory( + DWRITE_FACTORY_TYPE_SHARED, __uuidof(IDWriteFactory), + reinterpret_cast(dwrite_factory_.GetAddressOf()))); + + ThrowIfFailed(dwrite_factory_->GetSystemFontCollection( + &dwrite_system_font_collection_)); +} + +DirectGraphFactory::~DirectGraphFactory() { UninitializeCom(); } + +Microsoft::WRL::ComPtr +DirectGraphFactory::CreateD2D1DeviceContext() { + Microsoft::WRL::ComPtr d2d1_device_context; + ThrowIfFailed(d2d1_device_->CreateDeviceContext( + D2D1_DEVICE_CONTEXT_OPTIONS_NONE, &d2d1_device_context)); + return d2d1_device_context; +} + +std::unique_ptr DirectGraphFactory::CreateSolidColorBrush() { + return std::make_unique(this); +} + +std::unique_ptr DirectGraphFactory::CreateGeometryBuilder() { + return std::make_unique(this); +} + +std::unique_ptr DirectGraphFactory::CreateFont( + std::u16string font_family, float font_size) { + return std::make_unique(this, std::move(font_family), font_size); +} + +std::unique_ptr DirectGraphFactory::CreateTextLayout( + std::shared_ptr font, std::u16string text) { + return std::make_unique(this, std::move(font), + std::move(text)); +} +} // namespace cru::platform::graphics::win::direct diff --git a/src/win/graphics/direct/Font.cpp b/src/win/graphics/direct/Font.cpp new file mode 100644 index 00000000..1d6a5c88 --- /dev/null +++ b/src/win/graphics/direct/Font.cpp @@ -0,0 +1,31 @@ +#include "cru/win/graphics/direct/Font.hpp" + +#include "cru/win/graphics/direct/Exception.hpp" +#include "cru/win/graphics/direct/Factory.hpp" + +#include +#include + +namespace cru::platform::graphics::win::direct { +DWriteFont::DWriteFont(DirectGraphFactory* factory, std::u16string font_family, + float font_size) + : DirectGraphResource(factory), font_family_(std::move(font_family)) { + // Get locale + std::array buffer; + if (!::GetUserDefaultLocaleName(buffer.data(), + static_cast(buffer.size()))) + throw platform::win::Win32Error( + ::GetLastError(), "Failed to get locale when create dwrite font."); + + ThrowIfFailed(factory->GetDWriteFactory()->CreateTextFormat( + reinterpret_cast(font_family_.c_str()), nullptr, + DWRITE_FONT_WEIGHT_NORMAL, DWRITE_FONT_STYLE_NORMAL, + DWRITE_FONT_STRETCH_NORMAL, font_size, buffer.data(), &text_format_)); + + ThrowIfFailed(text_format_->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING)); + ThrowIfFailed( + text_format_->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR)); +} + +float DWriteFont::GetFontSize() { return text_format_->GetFontSize(); } +} // namespace cru::platform::graphics::win::direct diff --git a/src/win/graphics/direct/Geometry.cpp b/src/win/graphics/direct/Geometry.cpp new file mode 100644 index 00000000..8aa961b2 --- /dev/null +++ b/src/win/graphics/direct/Geometry.cpp @@ -0,0 +1,62 @@ +#include "cru/win/graphics/direct/Geometry.hpp" + +#include "cru/win/graphics/direct/ConvertUtil.hpp" +#include "cru/win/graphics/direct/Exception.hpp" +#include "cru/win/graphics/direct/Factory.hpp" + +namespace cru::platform::graphics::win::direct { +D2DGeometryBuilder::D2DGeometryBuilder(DirectGraphFactory* factory) + : DirectGraphResource(factory) { + ThrowIfFailed(factory->GetD2D1Factory()->CreatePathGeometry(&geometry_)); + ThrowIfFailed(geometry_->Open(&geometry_sink_)); +} + +void D2DGeometryBuilder::CheckValidation() { + if (!IsValid()) + throw ReuseException("The geometry builder is already disposed."); +} + +void D2DGeometryBuilder::BeginFigure(const Point& point) { + CheckValidation(); + geometry_sink_->BeginFigure(Convert(point), D2D1_FIGURE_BEGIN_FILLED); +} + +void D2DGeometryBuilder::LineTo(const Point& point) { + CheckValidation(); + geometry_sink_->AddLine(Convert(point)); +} + +void D2DGeometryBuilder::QuadraticBezierTo(const Point& control_point, + const Point& end_point) { + CheckValidation(); + geometry_sink_->AddQuadraticBezier( + D2D1::QuadraticBezierSegment(Convert(control_point), Convert(end_point))); +} + +void D2DGeometryBuilder::CloseFigure(bool close) { + CheckValidation(); + geometry_sink_->EndFigure(close ? D2D1_FIGURE_END_CLOSED + : D2D1_FIGURE_END_OPEN); +} + +std::unique_ptr D2DGeometryBuilder::Build() { + CheckValidation(); + ThrowIfFailed(geometry_sink_->Close()); + geometry_sink_ = nullptr; + auto geometry = + std::make_unique(GetDirectFactory(), std::move(geometry_)); + geometry_ = nullptr; + return geometry; +} + +D2DGeometry::D2DGeometry(DirectGraphFactory* factory, + Microsoft::WRL::ComPtr geometry) + : DirectGraphResource(factory), geometry_(std::move(geometry)) {} + +bool D2DGeometry::FillContains(const Point& point) { + BOOL result; + ThrowIfFailed(geometry_->FillContainsPoint( + Convert(point), D2D1::Matrix3x2F::Identity(), &result)); + return result != 0; +} +} // namespace cru::platform::graphics::win::direct diff --git a/src/win/graphics/direct/Painter.cpp b/src/win/graphics/direct/Painter.cpp new file mode 100644 index 00000000..91392ba7 --- /dev/null +++ b/src/win/graphics/direct/Painter.cpp @@ -0,0 +1,104 @@ +#include "cru/win/graphics/direct/Painter.hpp" + +#include "cru/platform/Check.hpp" +#include "cru/win/graphics/direct/Brush.hpp" +#include "cru/win/graphics/direct/ConvertUtil.hpp" +#include "cru/win/graphics/direct/Exception.hpp" +#include "cru/win/graphics/direct/Geometry.hpp" +#include "cru/win/graphics/direct/TextLayout.hpp" + +#include + +namespace cru::platform::graphics::win::direct { +D2DPainter::D2DPainter(ID2D1RenderTarget* render_target) { + Expects(render_target); + render_target_ = render_target; +} + +platform::Matrix D2DPainter::GetTransform() { + CheckValidation(); + D2D1_MATRIX_3X2_F m; + render_target_->GetTransform(&m); + return Convert(m); +} + +void D2DPainter::SetTransform(const platform::Matrix& matrix) { + CheckValidation(); + render_target_->SetTransform(Convert(matrix)); +} + +void D2DPainter::Clear(const Color& color) { + CheckValidation(); + render_target_->Clear(Convert(color)); +} + +void D2DPainter::StrokeRectangle(const Rect& rectangle, IBrush* brush, + float width) { + CheckValidation(); + const auto b = CheckPlatform(brush, GetPlatformId()); + render_target_->DrawRectangle(Convert(rectangle), b->GetD2DBrushInterface(), + width); +} + +void D2DPainter::FillRectangle(const Rect& rectangle, IBrush* brush) { + CheckValidation(); + const auto b = CheckPlatform(brush, GetPlatformId()); + render_target_->FillRectangle(Convert(rectangle), b->GetD2DBrushInterface()); +} + +void D2DPainter::StrokeGeometry(IGeometry* geometry, IBrush* brush, + float width) { + CheckValidation(); + const auto g = CheckPlatform(geometry, GetPlatformId()); + const auto b = CheckPlatform(brush, GetPlatformId()); + render_target_->DrawGeometry(g->GetComInterface(), b->GetD2DBrushInterface(), + width); +} + +void D2DPainter::FillGeometry(IGeometry* geometry, IBrush* brush) { + CheckValidation(); + const auto g = CheckPlatform(geometry, GetPlatformId()); + const auto b = CheckPlatform(brush, GetPlatformId()); + render_target_->FillGeometry(g->GetComInterface(), b->GetD2DBrushInterface()); +} + +void D2DPainter::DrawText(const Point& offset, ITextLayout* text_layout, + IBrush* brush) { + CheckValidation(); + const auto t = CheckPlatform(text_layout, GetPlatformId()); + const auto b = CheckPlatform(brush, GetPlatformId()); + render_target_->DrawTextLayout(Convert(offset), t->GetComInterface(), + b->GetD2DBrushInterface()); +} + +void D2DPainter::PushLayer(const Rect& bounds) { + CheckValidation(); + + Microsoft::WRL::ComPtr layer; + ThrowIfFailed(render_target_->CreateLayer(&layer)); + + render_target_->PushLayer(D2D1::LayerParameters(Convert(bounds)), + layer.Get()); + + layers_.push_back(std::move(layer)); +} + +void D2DPainter::PopLayer() { + render_target_->PopLayer(); + layers_.pop_back(); +} + +void D2DPainter::EndDraw() { + if (is_drawing_) { + is_drawing_ = false; + DoEndDraw(); + } +} + +void D2DPainter::CheckValidation() { + if (!is_drawing_) { + throw cru::platform::ReuseException( + "Can't do that on painter after end drawing."); + } +} +} // namespace cru::platform::graphics::win::direct diff --git a/src/win/graphics/direct/Resource.cpp b/src/win/graphics/direct/Resource.cpp new file mode 100644 index 00000000..2b4a0772 --- /dev/null +++ b/src/win/graphics/direct/Resource.cpp @@ -0,0 +1,12 @@ +#include "cru/win/graphics/direct/Resource.hpp" + +#include "cru/win/graphics/direct/Factory.hpp" + +namespace cru::platform::graphics::win::direct { +DirectGraphResource::DirectGraphResource(DirectGraphFactory* factory) + : factory_(factory) { + Expects(factory); +} + +IGraphFactory* DirectGraphResource::GetGraphFactory() { return factory_; } +} // namespace cru::platform::graphics::win::direct diff --git a/src/win/graphics/direct/TextLayout.cpp b/src/win/graphics/direct/TextLayout.cpp new file mode 100644 index 00000000..0c6e797f --- /dev/null +++ b/src/win/graphics/direct/TextLayout.cpp @@ -0,0 +1,124 @@ +#include "cru/win/graphics/direct/TextLayout.hpp" + +#include "cru/common/Logger.hpp" +#include "cru/platform/Check.hpp" +#include "cru/win/graphics/direct/Exception.hpp" +#include "cru/win/graphics/direct/Factory.hpp" +#include "cru/win/graphics/direct/Font.hpp" + +#include + +namespace cru::platform::graphics::win::direct { +DWriteTextLayout::DWriteTextLayout(DirectGraphFactory* factory, + std::shared_ptr font, + std::u16string text) + : DirectGraphResource(factory), text_(std::move(text)) { + Expects(font); + font_ = CheckPlatform(font, GetPlatformId()); + + ThrowIfFailed(factory->GetDWriteFactory()->CreateTextLayout( + reinterpret_cast(text_.c_str()), + static_cast(text_.size()), font_->GetComInterface(), max_width_, + max_height_, &text_layout_)); +} + +DWriteTextLayout::~DWriteTextLayout() = default; + +std::u16string DWriteTextLayout::GetText() { return text_; } + +std::u16string_view DWriteTextLayout::GetTextView() { return text_; } + +void DWriteTextLayout::SetText(std::u16string new_text) { + text_.swap(new_text); + ThrowIfFailed(GetDirectFactory()->GetDWriteFactory()->CreateTextLayout( + reinterpret_cast(text_.c_str()), + static_cast(text_.size()), font_->GetComInterface(), max_width_, + max_height_, &text_layout_)); +} + +std::shared_ptr DWriteTextLayout::GetFont() { + return std::dynamic_pointer_cast(font_); +} + +void DWriteTextLayout::SetFont(std::shared_ptr font) { + font_ = CheckPlatform(font, GetPlatformId()); + ThrowIfFailed(GetDirectFactory()->GetDWriteFactory()->CreateTextLayout( + reinterpret_cast(text_.c_str()), + static_cast(text_.size()), font_->GetComInterface(), max_width_, + max_height_, &text_layout_)); +} + +void DWriteTextLayout::SetMaxWidth(float max_width) { + max_width_ = max_width; + ThrowIfFailed(text_layout_->SetMaxWidth(max_width_)); +} + +void DWriteTextLayout::SetMaxHeight(float max_height) { + max_height_ = max_height; + ThrowIfFailed(text_layout_->SetMaxHeight(max_height_)); +} + +Rect DWriteTextLayout::GetTextBounds() { + DWRITE_TEXT_METRICS metrics; + ThrowIfFailed(text_layout_->GetMetrics(&metrics)); + return Rect{metrics.left, metrics.top, metrics.width, metrics.height}; +} + +std::vector DWriteTextLayout::TextRangeRect( + const TextRange& text_range_arg) { + if (text_range_arg.count == 0) { + return {}; + } + const auto text_range = text_range_arg.Normalize(); + + DWRITE_TEXT_METRICS text_metrics; + ThrowIfFailed(text_layout_->GetMetrics(&text_metrics)); + const auto metrics_count = + text_metrics.lineCount * text_metrics.maxBidiReorderingDepth; + + std::vector hit_test_metrics(metrics_count); + UINT32 actual_count; + ThrowIfFailed(text_layout_->HitTestTextRange( + static_cast(text_range.position), + static_cast(text_range.count), 0, 0, hit_test_metrics.data(), + metrics_count, &actual_count)); + + hit_test_metrics.erase(hit_test_metrics.cbegin() + actual_count, + hit_test_metrics.cend()); + + std::vector result; + result.reserve(actual_count); + + for (const auto& metrics : hit_test_metrics) { + result.push_back( + Rect{metrics.left, metrics.top, metrics.width, metrics.height}); + } + + return result; +} + +Point DWriteTextLayout::TextSinglePoint(Index position, bool trailing) { + DWRITE_HIT_TEST_METRICS metrics; + FLOAT left; + FLOAT top; + ThrowIfFailed(text_layout_->HitTestTextPosition(static_cast(position), + static_cast(trailing), + &left, &top, &metrics)); + return Point{left, top}; +} + +TextHitTestResult DWriteTextLayout::HitTest(const Point& point) { + BOOL trailing; + BOOL inside; + DWRITE_HIT_TEST_METRICS metrics; + + ThrowIfFailed(text_layout_->HitTestPoint(point.x, point.y, &trailing, &inside, + &metrics)); + + TextHitTestResult result; + result.position = metrics.textPosition; + result.trailing = trailing != 0; + result.insideText = inside != 0; + return result; +} +} // namespace cru::platform::graphics::win::direct diff --git a/src/win/graphics/direct/WindowPainter.cpp b/src/win/graphics/direct/WindowPainter.cpp new file mode 100644 index 00000000..c88667b6 --- /dev/null +++ b/src/win/graphics/direct/WindowPainter.cpp @@ -0,0 +1,20 @@ +#include "cru/win/graphics/direct/WindowPainter.hpp" + +#include "cru/win/graphics/direct/Exception.hpp" +#include "cru/win/graphics/direct/Factory.hpp" +#include "cru/win/graphics/direct/WindowRenderTarget.hpp" + +namespace cru::platform::graphics::win::direct { +D2DWindowPainter::D2DWindowPainter(D2DWindowRenderTarget* render_target) + : D2DPainter(render_target->GetD2D1DeviceContext()), + render_target_(render_target) { + render_target_->GetD2D1DeviceContext()->BeginDraw(); +} + +D2DWindowPainter::~D2DWindowPainter() { EndDraw(); } + +void D2DWindowPainter::DoEndDraw() { + ThrowIfFailed(render_target_->GetD2D1DeviceContext()->EndDraw()); + render_target_->Present(); +} +} // namespace cru::platform::graphics::win::direct diff --git a/src/win/graphics/direct/WindowRenderTarget.cpp b/src/win/graphics/direct/WindowRenderTarget.cpp new file mode 100644 index 00000000..7479ae24 --- /dev/null +++ b/src/win/graphics/direct/WindowRenderTarget.cpp @@ -0,0 +1,81 @@ +#include "cru/win/graphics/direct/WindowRenderTarget.hpp" + +#include "cru/win/graphics/direct/Exception.hpp" +#include "cru/win/graphics/direct/Factory.hpp" + +namespace cru::platform::graphics::win::direct { +D2DWindowRenderTarget::D2DWindowRenderTarget( + gsl::not_null factory, HWND hwnd) + : factory_(factory), hwnd_(hwnd) { + const auto d3d11_device = factory->GetD3D11Device(); + const auto dxgi_factory = factory->GetDxgiFactory(); + + d2d1_device_context_ = factory->CreateD2D1DeviceContext(); + d2d1_device_context_->SetUnitMode(D2D1_UNIT_MODE_DIPS); + + // Allocate a descriptor. + DXGI_SWAP_CHAIN_DESC1 swap_chain_desc; + swap_chain_desc.Width = 0; // use automatic sizing + swap_chain_desc.Height = 0; + swap_chain_desc.Format = + DXGI_FORMAT_B8G8R8A8_UNORM; // this is the most common swapchain format + swap_chain_desc.Stereo = false; + swap_chain_desc.SampleDesc.Count = 1; // don't use multi-sampling + swap_chain_desc.SampleDesc.Quality = 0; + swap_chain_desc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; + swap_chain_desc.BufferCount = 2; // use double buffering to enable flip + swap_chain_desc.Scaling = DXGI_SCALING_NONE; + swap_chain_desc.SwapEffect = + DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL; // all apps must use this SwapEffect + swap_chain_desc.AlphaMode = DXGI_ALPHA_MODE_UNSPECIFIED; + swap_chain_desc.Flags = 0; + + // Get the final swap chain for this window from the DXGI factory. + ThrowIfFailed(dxgi_factory->CreateSwapChainForHwnd( + d3d11_device, hwnd, &swap_chain_desc, nullptr, nullptr, + &dxgi_swap_chain_)); + + CreateTargetBitmap(); +} + +void D2DWindowRenderTarget::SetDpi(float x, float y) { + d2d1_device_context_->SetDpi(x, y); +} + +void D2DWindowRenderTarget::ResizeBuffer(const int width, const int height) { + // In order to resize buffer, we need to untarget the buffer first. + d2d1_device_context_->SetTarget(nullptr); + target_bitmap_ = nullptr; + ThrowIfFailed(dxgi_swap_chain_->ResizeBuffers(0, width, height, + DXGI_FORMAT_UNKNOWN, 0)); + CreateTargetBitmap(); +} + +void D2DWindowRenderTarget::Present() { + ThrowIfFailed(dxgi_swap_chain_->Present(1, 0)); +} + +void D2DWindowRenderTarget::CreateTargetBitmap() { + Expects(target_bitmap_ == nullptr); // target bitmap must not exist. + + // Direct2D needs the dxgi version of the backbuffer surface pointer. + Microsoft::WRL::ComPtr dxgi_back_buffer; + ThrowIfFailed( + dxgi_swap_chain_->GetBuffer(0, IID_PPV_ARGS(&dxgi_back_buffer))); + + float dpi_x, dpi_y; + d2d1_device_context_->GetDpi(&dpi_x, &dpi_y); + + auto bitmap_properties = D2D1::BitmapProperties1( + D2D1_BITMAP_OPTIONS_TARGET | D2D1_BITMAP_OPTIONS_CANNOT_DRAW, + D2D1::PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_IGNORE), + dpi_x, dpi_y); + + // Get a D2D surface from the DXGI back buffer to use as the D2D render + // target. + ThrowIfFailed(d2d1_device_context_->CreateBitmapFromDxgiSurface( + dxgi_back_buffer.Get(), &bitmap_properties, &target_bitmap_)); + + d2d1_device_context_->SetTarget(target_bitmap_.Get()); +} +} // namespace cru::platform::graphics::win::direct diff --git a/src/win/gui/CMakeLists.txt b/src/win/gui/CMakeLists.txt new file mode 100644 index 00000000..48bed00d --- /dev/null +++ b/src/win/gui/CMakeLists.txt @@ -0,0 +1,31 @@ +set(CRU_WIN_GUI_INCLUDE_DIR ${CRU_INCLUDE_DIR}/cru/win/gui) + +add_library(cru_win_gui STATIC + TimerManager.hpp + WindowManager.hpp + + Cursor.cpp + GodWindow.cpp + InputMethod.cpp + Keyboard.cpp + TimerManager.cpp + UiApplication.cpp + Window.cpp + WindowClass.cpp + WindowManager.cpp +) +target_sources(cru_win_gui PUBLIC + ${CRU_WIN_GUI_INCLUDE_DIR}/Cursor.hpp + ${CRU_WIN_GUI_INCLUDE_DIR}/Exception.hpp + ${CRU_WIN_GUI_INCLUDE_DIR}/Base.hpp + ${CRU_WIN_GUI_INCLUDE_DIR}/GodWindow.hpp + ${CRU_WIN_GUI_INCLUDE_DIR}/InputMethod.hpp + ${CRU_WIN_GUI_INCLUDE_DIR}/Keyboard.hpp + ${CRU_WIN_GUI_INCLUDE_DIR}/Resource.hpp + ${CRU_WIN_GUI_INCLUDE_DIR}/UiApplication.hpp + ${CRU_WIN_GUI_INCLUDE_DIR}/Window.hpp + ${CRU_WIN_GUI_INCLUDE_DIR}/WindowClass.hpp + ${CRU_WIN_GUI_INCLUDE_DIR}/WindowNativeMessageEventArgs.hpp +) +target_link_libraries(cru_win_gui PUBLIC imm32) +target_link_libraries(cru_win_gui PUBLIC cru_win_graphics_direct cru_platform_gui) diff --git a/src/win/gui/Cursor.cpp b/src/win/gui/Cursor.cpp new file mode 100644 index 00000000..5f3086fa --- /dev/null +++ b/src/win/gui/Cursor.cpp @@ -0,0 +1,51 @@ +#include "cru/win/gui/Cursor.hpp" + +#include "cru/common/Logger.hpp" +#include "cru/win/gui/Exception.hpp" + +#include + +namespace cru::platform::gui::win { +WinCursor::WinCursor(HCURSOR handle, bool auto_destroy) { + handle_ = handle; + auto_destroy_ = auto_destroy; +} + +WinCursor::~WinCursor() { + if (auto_destroy_) { + if (!::DestroyCursor(handle_)) { + // This is not a fetal error but might still need notice because it may + // cause leak. + log::TagWarn(log_tag, u"Failed to destroy a cursor. Last error code: {}", + ::GetLastError()); + } + } +} + +namespace { +WinCursor* LoadWinCursor(const wchar_t* name) { + const auto handle = static_cast(::LoadImageW( + NULL, name, IMAGE_CURSOR, SM_CYCURSOR, SM_CYCURSOR, LR_SHARED)); + if (handle == NULL) { + throw Win32Error(::GetLastError(), "Failed to load system cursor."); + } + return new WinCursor(handle, false); +} +} // namespace + +WinCursorManager::WinCursorManager() + : sys_arrow_(LoadWinCursor(IDC_ARROW)), + sys_hand_(LoadWinCursor(IDC_HAND)) {} + +std::shared_ptr WinCursorManager::GetSystemWinCursor( + SystemCursorType type) { + switch (type) { + case SystemCursorType::Arrow: + return sys_arrow_; + case SystemCursorType::Hand: + return sys_hand_; + default: + throw std::runtime_error("Unknown system cursor value."); + } +} +} // namespace cru::platform::gui::win diff --git a/src/win/gui/GodWindow.cpp b/src/win/gui/GodWindow.cpp new file mode 100644 index 00000000..7bce83a3 --- /dev/null +++ b/src/win/gui/GodWindow.cpp @@ -0,0 +1,63 @@ +#include "cru/win/gui/GodWindow.hpp" + +#include "cru/common/Logger.hpp" +#include "cru/win/gui/Exception.hpp" +#include "cru/win/gui/UiApplication.hpp" +#include "cru/win/gui/WindowClass.hpp" + +namespace cru::platform::gui::win { +constexpr auto god_window_class_name = L"GodWindowClass"; + +LRESULT CALLBACK GodWndProc(HWND hWnd, UINT uMsg, WPARAM wParam, + LPARAM lParam) { + const auto app = WinUiApplication::GetInstance(); + + if (app) { + LRESULT result; + auto god_window = app->GetGodWindow(); + if (god_window != nullptr) { + const auto handled = god_window->HandleGodWindowMessage( + hWnd, uMsg, wParam, lParam, &result); + if (handled) return result; + } + } + return DefWindowProcW(hWnd, uMsg, wParam, lParam); +} + +GodWindow::GodWindow(WinUiApplication* application) { + application_ = application; + + const auto h_instance = application->GetInstanceHandle(); + + god_window_class_ = std::make_unique(god_window_class_name, + GodWndProc, h_instance); + + hwnd_ = CreateWindowEx(0, god_window_class_name, L"", 0, CW_USEDEFAULT, + CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, + HWND_MESSAGE, nullptr, h_instance, nullptr); + + if (hwnd_ == nullptr) + throw Win32Error(::GetLastError(), "Failed to create god window."); +} + +GodWindow::~GodWindow() { + if (!::DestroyWindow(hwnd_)) { + // Although this could be "safely" ignore. + log::TagWarn(log_tag, u"Failed to destroy god window."); + } +} + +bool GodWindow::HandleGodWindowMessage(HWND hwnd, UINT msg, WPARAM w_param, + LPARAM l_param, LRESULT* result) { + WindowNativeMessageEventArgs args( + WindowNativeMessage{hwnd, msg, w_param, l_param}); + message_event_.Raise(args); + + if (args.IsHandled()) { + *result = args.GetResult(); + return true; + } + + return false; +} +} // namespace cru::platform::gui::win diff --git a/src/win/gui/InputMethod.cpp b/src/win/gui/InputMethod.cpp new file mode 100644 index 00000000..d6f2146d --- /dev/null +++ b/src/win/gui/InputMethod.cpp @@ -0,0 +1,278 @@ +#include "cru/win/gui/InputMethod.hpp" + +#include "cru/common/Logger.hpp" +#include "cru/common/StringUtil.hpp" +#include "cru/platform/Check.hpp" +#include "cru/win/Exception.hpp" +#include "cru/win/gui/Window.hpp" + +#include + +namespace cru::platform::gui::win { +AutoHIMC::AutoHIMC(HWND hwnd) : hwnd_(hwnd) { + Expects(hwnd); + handle_ = ::ImmGetContext(hwnd); +} + +AutoHIMC::AutoHIMC(AutoHIMC&& other) + : hwnd_(other.hwnd_), handle_(other.handle_) { + other.hwnd_ = nullptr; + other.handle_ = nullptr; +} + +AutoHIMC& AutoHIMC::operator=(AutoHIMC&& other) { + if (this != &other) { + Object::operator=(std::move(other)); + this->hwnd_ = other.hwnd_; + this->handle_ = other.handle_; + other.hwnd_ = nullptr; + other.handle_ = nullptr; + } + return *this; +} + +AutoHIMC::~AutoHIMC() { + if (handle_) { + if (!::ImmReleaseContext(hwnd_, handle_)) + log::TagWarn(log_tag, u"Failed to release HIMC."); + } +} + +// copied from chromium +namespace { +// Determines whether or not the given attribute represents a target +// (a.k.a. a selection). +bool IsTargetAttribute(char attribute) { + return (attribute == ATTR_TARGET_CONVERTED || + attribute == ATTR_TARGET_NOTCONVERTED); +} +// Helper function for ImeInput::GetCompositionInfo() method, to get the target +// range that's selected by the user in the current composition string. +void GetCompositionTargetRange(HIMC imm_context, int* target_start, + int* target_end) { + int attribute_size = + ::ImmGetCompositionString(imm_context, GCS_COMPATTR, NULL, 0); + if (attribute_size > 0) { + int start = 0; + int end = 0; + std::vector attribute_data(attribute_size); + ::ImmGetCompositionString(imm_context, GCS_COMPATTR, attribute_data.data(), + attribute_size); + for (start = 0; start < attribute_size; ++start) { + if (IsTargetAttribute(attribute_data[start])) break; + } + for (end = start; end < attribute_size; ++end) { + if (!IsTargetAttribute(attribute_data[end])) break; + } + if (start == attribute_size) { + // This composition clause does not contain any target clauses, + // i.e. this clauses is an input clause. + // We treat the whole composition as a target clause. + start = 0; + end = attribute_size; + } + *target_start = start; + *target_end = end; + } +} +// Helper function for ImeInput::GetCompositionInfo() method, to get underlines +// information of the current composition string. +CompositionClauses GetCompositionClauses(HIMC imm_context, int target_start, + int target_end) { + CompositionClauses result; + int clause_size = + ::ImmGetCompositionString(imm_context, GCS_COMPCLAUSE, NULL, 0); + int clause_length = clause_size / sizeof(std::uint32_t); + if (clause_length) { + result.reserve(clause_length - 1); + std::vector clause_data(clause_length); + ::ImmGetCompositionString(imm_context, GCS_COMPCLAUSE, clause_data.data(), + clause_size); + for (int i = 0; i < clause_length - 1; ++i) { + CompositionClause clause; + clause.start = clause_data[i]; + clause.end = clause_data[i + 1]; + clause.target = false; + // Use thick underline for the target clause. + if (clause.start >= target_start && clause.end <= target_end) { + clause.target = true; + } + result.push_back(clause); + } + } + return result; +} + +std::u16string GetString(HIMC imm_context) { + LONG string_size = + ::ImmGetCompositionString(imm_context, GCS_COMPSTR, NULL, 0); + std::u16string result((string_size / sizeof(char16_t)), 0); + ::ImmGetCompositionString(imm_context, GCS_COMPSTR, result.data(), + string_size); + return result; +} + +std::u16string GetResultString(HIMC imm_context) { + LONG string_size = + ::ImmGetCompositionString(imm_context, GCS_RESULTSTR, NULL, 0); + std::u16string result((string_size / sizeof(char16_t)), 0); + ::ImmGetCompositionString(imm_context, GCS_RESULTSTR, result.data(), + string_size); + return result; +} + +CompositionText GetCompositionInfo(HIMC imm_context) { + // We only care about GCS_COMPATTR, GCS_COMPCLAUSE and GCS_CURSORPOS, and + // convert them into underlines and selection range respectively. + + auto text = GetString(imm_context); + + int length = static_cast(text.length()); + // Find out the range selected by the user. + int target_start = length; + int target_end = length; + GetCompositionTargetRange(imm_context, &target_start, &target_end); + + auto clauses = GetCompositionClauses(imm_context, target_start, target_end); + + int cursor = ::ImmGetCompositionString(imm_context, GCS_CURSORPOS, NULL, 0); + + return CompositionText{std::move(text), std::move(clauses), + TextRange{cursor}}; +} + +} // namespace + +WinInputMethodContext::WinInputMethodContext( + gsl::not_null window) + : native_window_(window) { + event_guard_ += window->NativeMessageEvent()->AddHandler( + std::bind(&WinInputMethodContext::OnWindowNativeMessage, this, + std::placeholders::_1)); +} + +WinInputMethodContext::~WinInputMethodContext() {} + +void WinInputMethodContext::EnableIME() { + const auto hwnd = native_window_->GetWindowHandle(); + if (::ImmAssociateContextEx(hwnd, nullptr, IACE_DEFAULT) == FALSE) { + log::TagWarn(log_tag, u"Failed to enable ime."); + } +} + +void WinInputMethodContext::DisableIME() { + const auto hwnd = native_window_->GetWindowHandle(); + AutoHIMC himc{hwnd}; + + if (!::ImmNotifyIME(himc.Get(), NI_COMPOSITIONSTR, CPS_COMPLETE, 0)) { + log::TagWarn(log_tag, + u"Failed to complete composition before disable ime."); + } + + if (::ImmAssociateContextEx(hwnd, nullptr, 0) == FALSE) { + log::TagWarn(log_tag, u"Failed to disable ime."); + } +} + +void WinInputMethodContext::CompleteComposition() { + auto himc = GetHIMC(); + if (!::ImmNotifyIME(himc.Get(), NI_COMPOSITIONSTR, CPS_COMPLETE, 0)) { + log::TagWarn(log_tag, u"Failed to complete composition."); + } +} + +void WinInputMethodContext::CancelComposition() { + auto himc = GetHIMC(); + if (!::ImmNotifyIME(himc.Get(), NI_COMPOSITIONSTR, CPS_CANCEL, 0)) { + log::TagWarn(log_tag, u"Failed to complete composition."); + } +} + +CompositionText WinInputMethodContext::GetCompositionText() { + auto himc = GetHIMC(); + return GetCompositionInfo(himc.Get()); +} + +void WinInputMethodContext::SetCandidateWindowPosition(const Point& point) { + auto himc = GetHIMC(); + + ::CANDIDATEFORM form; + form.dwIndex = 1; + form.dwStyle = CFS_CANDIDATEPOS; + + form.ptCurrentPos = native_window_->DipToPixel(point); + + if (!::ImmSetCandidateWindow(himc.Get(), &form)) + log::TagDebug(log_tag, + u"Failed to set input method candidate window position."); +} + +IEvent* WinInputMethodContext::CompositionStartEvent() { + return &composition_start_event_; +} + +IEvent* WinInputMethodContext::CompositionEndEvent() { + return &composition_end_event_; +}; + +IEvent* WinInputMethodContext::CompositionEvent() { + return &composition_event_; +} + +IEvent* WinInputMethodContext::TextEvent() { + return &text_event_; +} + +void WinInputMethodContext::OnWindowNativeMessage( + WindowNativeMessageEventArgs& args) { + const auto& message = args.GetWindowMessage(); + switch (message.msg) { + case WM_CHAR: { + const auto c = static_cast(message.w_param); + if (IsUtf16SurrogatePairCodeUnit(c)) { + // I don't think this will happen because normal key strike without ime + // should only trigger ascci character. If it is a charater from + // supplementary planes, it should be handled with ime messages. + log::TagWarn(log_tag, + u"A WM_CHAR message for character from supplementary " + u"planes is ignored."); + } else { + char16_t s[1] = {c}; + text_event_.Raise({s, 1}); + } + args.HandleWithResult(0); + break; + } + case WM_IME_COMPOSITION: { + composition_event_.Raise(nullptr); + auto composition_text = GetCompositionText(); + log::TagDebug(log_tag, u"WM_IME_COMPOSITION composition text:\n{}", + composition_text); + if (message.l_param & GCS_RESULTSTR) { + auto result_string = GetResultString(); + text_event_.Raise(result_string); + } + break; + } + case WM_IME_STARTCOMPOSITION: { + composition_start_event_.Raise(nullptr); + break; + } + case WM_IME_ENDCOMPOSITION: { + composition_end_event_.Raise(nullptr); + break; + } + } +} + +std::u16string WinInputMethodContext::GetResultString() { + auto himc = GetHIMC(); + auto result = win::GetResultString(himc.Get()); + return result; +} + +AutoHIMC WinInputMethodContext::GetHIMC() { + const auto hwnd = native_window_->GetWindowHandle(); + return AutoHIMC{hwnd}; +} +} // namespace cru::platform::gui::win diff --git a/src/win/gui/Keyboard.cpp b/src/win/gui/Keyboard.cpp new file mode 100644 index 00000000..b706b240 --- /dev/null +++ b/src/win/gui/Keyboard.cpp @@ -0,0 +1,74 @@ +#include "cru/win/gui/Keyboard.hpp" + +namespace cru::platform::gui::win { +KeyCode VirtualKeyToKeyCode(int virtual_key) { + if (virtual_key >= 0x30 && virtual_key <= 0x39) { + return KeyCode{static_cast(KeyCode::N0) + (virtual_key - 0x30)}; + } else if (virtual_key >= 0x41 && virtual_key <= 0x5a) { + return KeyCode{static_cast(KeyCode::A) + (virtual_key - 0x41)}; + } else if (virtual_key >= VK_NUMPAD0 && virtual_key <= VK_NUMPAD9) { + return KeyCode{static_cast(KeyCode::NumPad0) + + (virtual_key - VK_NUMPAD0)}; + } else if (virtual_key >= VK_F1 && virtual_key <= VK_F12) { + return KeyCode{static_cast(KeyCode::F1) + (virtual_key - VK_F1)}; + } else { + switch (virtual_key) { +#define CRU_MAP_KEY(virtual_key, keycode) \ + case virtual_key: \ + return KeyCode::keycode; + + CRU_MAP_KEY(VK_LBUTTON, LeftButton) + CRU_MAP_KEY(VK_MBUTTON, MiddleButton) + CRU_MAP_KEY(VK_RBUTTON, RightButton) + CRU_MAP_KEY(VK_ESCAPE, Escape) + CRU_MAP_KEY(VK_OEM_3, GraveAccent) + CRU_MAP_KEY(VK_TAB, Tab) + CRU_MAP_KEY(VK_CAPITAL, CapsLock) + CRU_MAP_KEY(VK_LSHIFT, LeftShift) + CRU_MAP_KEY(VK_LCONTROL, LeftCtrl) + CRU_MAP_KEY(VK_LWIN, LeftSuper) + CRU_MAP_KEY(VK_LMENU, LeftAlt) + CRU_MAP_KEY(VK_OEM_MINUS, Minus) + CRU_MAP_KEY(VK_OEM_PLUS, Equal) + CRU_MAP_KEY(VK_BACK, Backspace) + CRU_MAP_KEY(VK_OEM_4, LeftSquareBracket) + CRU_MAP_KEY(VK_OEM_6, RightSquareBracket) + CRU_MAP_KEY(VK_OEM_5, BackSlash) + CRU_MAP_KEY(VK_OEM_1, Semicolon) + CRU_MAP_KEY(VK_OEM_7, Quote) + CRU_MAP_KEY(VK_OEM_COMMA, Comma) + CRU_MAP_KEY(VK_OEM_PERIOD, Period) + CRU_MAP_KEY(VK_OEM_2, Slash) + CRU_MAP_KEY(VK_RSHIFT, RightShift) + CRU_MAP_KEY(VK_RCONTROL, RightCtrl) + CRU_MAP_KEY(VK_RWIN, RightSuper) + CRU_MAP_KEY(VK_RMENU, RightAlt) + CRU_MAP_KEY(VK_INSERT, Insert) + CRU_MAP_KEY(VK_DELETE, Delete) + CRU_MAP_KEY(VK_HOME, Home) + CRU_MAP_KEY(VK_END, End) + CRU_MAP_KEY(VK_PRIOR, PageUp) + CRU_MAP_KEY(VK_NEXT, PageDown) + CRU_MAP_KEY(VK_UP, Up) + CRU_MAP_KEY(VK_LEFT, Left) + CRU_MAP_KEY(VK_DOWN, Down) + CRU_MAP_KEY(VK_RIGHT, Right) + CRU_MAP_KEY(VK_SNAPSHOT, PrintScreen) + CRU_MAP_KEY(VK_PAUSE, Pause) + +#undef CRU_MAP_KEY + + default: + return KeyCode::Unknown; + } + } +} + +KeyModifier RetrieveKeyMofifier() { + KeyModifier result{0}; + if (::GetKeyState(VK_SHIFT) < 0) result |= KeyModifiers::shift; + if (::GetKeyState(VK_CONTROL) < 0) result |= KeyModifiers::ctrl; + if (::GetKeyState(VK_MENU) < 0) result |= KeyModifiers::alt; + return result; +} +} // namespace cru::platform::gui::win diff --git a/src/win/gui/TimerManager.cpp b/src/win/gui/TimerManager.cpp new file mode 100644 index 00000000..fc26b6c4 --- /dev/null +++ b/src/win/gui/TimerManager.cpp @@ -0,0 +1,100 @@ +#include "TimerManager.hpp" + +#include "cru/win/gui/Base.hpp" +#include "cru/win/gui/Exception.hpp" +#include "gsl/gsl_util" + +#include +#include + +namespace cru::platform::gui::win { +constexpr int kSetImmediateWindowMessageId = WM_USER + 2000; + +TimerManager::TimerManager(GodWindow* god_window) { + god_window_ = god_window; + event_guard_ += god_window->MessageEvent()->AddHandler(std::bind( + &TimerManager::HandleGodWindowMessage, this, std::placeholders::_1)); +} + +long long TimerManager::SetTimer(TimerType type, int period, + std::function action) { + auto id = next_id_++; + TimerInfo timer_info{id, type, type == TimerType::Immediate ? 0 : period, + std::move(action)}; + if (type == TimerType::Immediate) { + if (!::PostMessageW(god_window_->GetHandle(), kSetImmediateWindowMessageId, + gsl::narrow(id), 0)) { + throw Win32Error( + ::GetLastError(), + "Failed to post window message to god window for set immediate."); + } + } else { + CreateNativeTimer(&timer_info); + } + + info_map_.emplace(id, std::move(timer_info)); + return id; +} + +void TimerManager::CancelTimer(long long id) { + if (id <= 0) return; + auto find_result = this->info_map_.find(id); + if (find_result != info_map_.cend()) { + auto& info = find_result->second; + KillNativeTimer(&info); + this->info_map_.erase(find_result); + } +} + +void TimerManager::CreateNativeTimer(TimerInfo* info) { + info->native_timer_id = gsl::narrow(info->id); + ::SetTimer(god_window_->GetHandle(), info->native_timer_id, info->period, + nullptr); +} + +void TimerManager::KillNativeTimer(TimerInfo* info) { + if (info->native_timer_id == 0) return; + ::KillTimer(god_window_->GetHandle(), info->native_timer_id); + info->native_timer_id = 0; +} + +void TimerManager::HandleGodWindowMessage(WindowNativeMessageEventArgs& args) { + const auto& message = args.GetWindowMessage(); + + switch (message.msg) { + case kSetImmediateWindowMessageId: { + auto find_result = + this->info_map_.find(static_cast(message.w_param)); + if (find_result != info_map_.cend()) { + auto& info = find_result->second; + info.action(); + info_map_.erase(find_result); + } + args.SetResult(0); + args.SetHandled(true); + return; + } + case WM_TIMER: { + auto find_result = + this->info_map_.find(static_cast(message.w_param)); + if (find_result != info_map_.cend()) { + auto& info = find_result->second; + if (info.type == TimerType::Interval) { + info.action(); + args.SetResult(0); + args.SetHandled(true); + } else if (info.type == TimerType::Timeout) { + info.action(); + KillNativeTimer(&info); + info_map_.erase(find_result); + args.SetResult(0); + args.SetHandled(true); + } + } + return; + } + default: + return; + } +} +} // namespace cru::platform::gui::win diff --git a/src/win/gui/TimerManager.hpp b/src/win/gui/TimerManager.hpp new file mode 100644 index 00000000..a8db1075 --- /dev/null +++ b/src/win/gui/TimerManager.hpp @@ -0,0 +1,61 @@ +#pragma once +#include "cru/common/Event.hpp" +#include "cru/win/WinPreConfig.hpp" + +#include "cru/common/Base.hpp" +#include "cru/win/gui/GodWindow.hpp" +#include "cru/win/gui/WindowNativeMessageEventArgs.hpp" + +#include +#include +#include +#include + +namespace cru::platform::gui::win { +enum class TimerType { Immediate, Timeout, Interval }; + +struct TimerInfo { + TimerInfo(long long id, TimerType type, int period, + std::function action, UINT_PTR native_timer_id = 0) + : id(id), + type(type), + period(period), + action(std::move(action)), + native_timer_id(native_timer_id) {} + + long long id; + TimerType type; + int period; // in milliseconds + std::function action; + UINT_PTR native_timer_id; +}; + +class TimerManager : public Object { + public: + TimerManager(GodWindow* god_window); + + CRU_DELETE_COPY(TimerManager) + CRU_DELETE_MOVE(TimerManager) + + ~TimerManager() override = default; + + // Period is in milliseconds. When type is immediate, it is not checked and + // used. + long long SetTimer(TimerType type, int period, std::function action); + void CancelTimer(long long id); + + private: + void HandleGodWindowMessage(WindowNativeMessageEventArgs& args); + + void CreateNativeTimer(TimerInfo* info); + void KillNativeTimer(TimerInfo* info); + + private: + GodWindow* god_window_; + + EventRevokerListGuard event_guard_; + + long long next_id_ = 1; + std::unordered_map info_map_; +}; +} // namespace cru::platform::gui::win diff --git a/src/win/gui/UiApplication.cpp b/src/win/gui/UiApplication.cpp new file mode 100644 index 00000000..5041a6c0 --- /dev/null +++ b/src/win/gui/UiApplication.cpp @@ -0,0 +1,118 @@ +#include "cru/win/gui/UiApplication.hpp" + +#include "../DebugLogger.hpp" +#include "../StdOutLogger.hpp" +#include "TimerManager.hpp" +#include "WindowManager.hpp" +#include "cru/common/Logger.hpp" +#include "cru/platform/Check.hpp" +#include "cru/win/graphics/direct/Factory.hpp" +#include "cru/win/gui/Cursor.hpp" +#include "cru/win/gui/Exception.hpp" +#include "cru/win/gui/GodWindow.hpp" +#include "cru/win/gui/InputMethod.hpp" +#include "cru/win/gui/Window.hpp" + +namespace cru::platform::gui { +std::unique_ptr CreateUiApplication() { + return std::make_unique(); +} +} // namespace cru::platform::gui + +namespace cru::platform::gui::win { +WinUiApplication* WinUiApplication::instance = nullptr; + +WinUiApplication::WinUiApplication() { + instance = this; + + instance_handle_ = ::GetModuleHandleW(nullptr); + if (!instance_handle_) + throw Win32Error("Failed to get module(instance) handle."); + + ::SetThreadDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE); + + log::Logger::GetInstance()->AddSource( + std::make_unique<::cru::platform::win::WinDebugLoggerSource>()); + log::Logger::GetInstance()->AddSource( + std::make_unique<::cru::platform::win::WinStdOutLoggerSource>()); + + graph_factory_ = + std::make_unique(); + + god_window_ = std::make_unique(this); + timer_manager_ = std::make_unique(god_window_.get()); + window_manager_ = std::make_unique(this); + cursor_manager_ = std::make_unique(); +} + +WinUiApplication::~WinUiApplication() { instance = nullptr; } + +int WinUiApplication::Run() { + MSG msg; + while (GetMessageW(&msg, nullptr, 0, 0)) { + TranslateMessage(&msg); + DispatchMessageW(&msg); + } + + for (const auto& handler : quit_handlers_) handler(); + + return static_cast(msg.wParam); +} + +void WinUiApplication::RequestQuit(const int quit_code) { + ::PostQuitMessage(quit_code); +} + +void WinUiApplication::AddOnQuitHandler(std::function handler) { + quit_handlers_.push_back(std::move(handler)); +} + +long long WinUiApplication::SetImmediate(std::function action) { + return this->timer_manager_->SetTimer(TimerType::Immediate, 0, + std::move(action)); +} + +long long WinUiApplication::SetTimeout(std::chrono::milliseconds milliseconds, + std::function action) { + return this->timer_manager_->SetTimer(TimerType::Timeout, + gsl::narrow(milliseconds.count()), + std::move(action)); +} + +long long WinUiApplication::SetInterval(std::chrono::milliseconds milliseconds, + std::function action) { + return this->timer_manager_->SetTimer(TimerType::Interval, + gsl::narrow(milliseconds.count()), + std::move(action)); +} + +void WinUiApplication::CancelTimer(long long id) { + timer_manager_->CancelTimer(id); +} + +std::vector WinUiApplication::GetAllWindow() { + const auto&& windows = window_manager_->GetAllWindows(); + std::vector result; + for (const auto w : windows) { + result.push_back(static_cast(w)); + } + return result; +} + +INativeWindow* WinUiApplication::CreateWindow(INativeWindow* parent) { + WinNativeWindow* p = nullptr; + if (parent != nullptr) { + p = CheckPlatform(parent, GetPlatformId()); + } + return new WinNativeWindow(this, window_manager_->GetGeneralWindowClass(), + WS_OVERLAPPEDWINDOW, p); +} + +cru::platform::graphics::IGraphFactory* WinUiApplication::GetGraphFactory() { + return graph_factory_.get(); +} + +ICursorManager* WinUiApplication::GetCursorManager() { + return cursor_manager_.get(); +} +} // namespace cru::platform::gui::win diff --git a/src/win/gui/Window.cpp b/src/win/gui/Window.cpp new file mode 100644 index 00000000..dda8a36a --- /dev/null +++ b/src/win/gui/Window.cpp @@ -0,0 +1,453 @@ +#include "cru/win/gui/Window.hpp" + +#include "WindowManager.hpp" +#include "cru/common/Logger.hpp" +#include "cru/platform/Check.hpp" +#include "cru/platform/gui/Base.hpp" +#include "cru/win/graphics/direct/WindowPainter.hpp" +#include "cru/win/gui/Cursor.hpp" +#include "cru/win/gui/Exception.hpp" +#include "cru/win/gui/InputMethod.hpp" +#include "cru/win/gui/Keyboard.hpp" +#include "cru/win/gui/UiApplication.hpp" +#include "cru/win/gui/WindowClass.hpp" + +#include +#include +#include + +namespace cru::platform::gui::win { +WinNativeWindow::WinNativeWindow(WinUiApplication* application, + WindowClass* window_class, DWORD window_style, + WinNativeWindow* parent) + : application_(application), parent_window_(parent) { + Expects(application); // application can't be null. + + if (parent != nullptr) { + throw new std::runtime_error("Can't use a invalid window as parent."); + } + + const auto window_manager = application->GetWindowManager(); + + hwnd_ = CreateWindowExW( + 0, window_class->GetName(), L"", window_style, CW_USEDEFAULT, + CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, + parent == nullptr ? nullptr : parent->GetWindowHandle(), nullptr, + application->GetInstanceHandle(), nullptr); + + if (hwnd_ == nullptr) + throw Win32Error(::GetLastError(), "Failed to create window."); + + auto dpi = ::GetDpiForWindow(hwnd_); + if (dpi == 0) + throw Win32Error(::GetLastError(), "Failed to get dpi of window."); + dpi_ = static_cast(dpi); + log::Debug(u"Dpi of window is {}.", dpi_); + + window_manager->RegisterWindow(hwnd_, this); + + SetCursor(application->GetCursorManager()->GetSystemCursor( + cru::platform::gui::SystemCursorType::Arrow)); + + window_render_target_ = + std::make_unique( + application->GetDirectFactory(), hwnd_); + window_render_target_->SetDpi(dpi_, dpi_); + + input_method_context_ = std::make_unique(this); + input_method_context_->DisableIME(); +} + +WinNativeWindow::~WinNativeWindow() { + if (!sync_flag_) { + sync_flag_ = true; + Close(); + } +} + +void WinNativeWindow::Close() { ::DestroyWindow(hwnd_); } + +bool WinNativeWindow::IsVisible() { return ::IsWindowVisible(hwnd_); } + +void WinNativeWindow::SetVisible(bool is_visible) { + is_visible ? ShowWindow(hwnd_, SW_SHOWNORMAL) : ShowWindow(hwnd_, SW_HIDE); +} +Size WinNativeWindow::GetClientSize() { + const auto pixel_rect = GetClientRectPixel(); + return Size(PixelToDip(pixel_rect.right), PixelToDip(pixel_rect.bottom)); +} + +void WinNativeWindow::SetClientSize(const Size& size) { + const auto window_style = + static_cast(GetWindowLongPtr(hwnd_, GWL_STYLE)); + const auto window_ex_style = + static_cast(GetWindowLongPtr(hwnd_, GWL_EXSTYLE)); + + RECT rect; + rect.left = 0; + rect.top = 0; + rect.right = DipToPixel(size.width); + rect.bottom = DipToPixel(size.height); + if (!AdjustWindowRectEx(&rect, window_style, FALSE, window_ex_style)) + throw Win32Error(::GetLastError(), "Failed to invoke AdjustWindowRectEx."); + + if (!SetWindowPos(hwnd_, nullptr, 0, 0, rect.right - rect.left, + rect.bottom - rect.top, SWP_NOZORDER | SWP_NOMOVE)) + throw Win32Error(::GetLastError(), "Failed to invoke SetWindowPos."); +} + +Rect WinNativeWindow::GetWindowRect() { + RECT rect; + if (!::GetWindowRect(hwnd_, &rect)) + throw Win32Error(::GetLastError(), "Failed to invoke GetWindowRect."); + + return Rect::FromVertices(PixelToDip(rect.left), PixelToDip(rect.top), + PixelToDip(rect.right), PixelToDip(rect.bottom)); +} + +void WinNativeWindow::SetWindowRect(const Rect& rect) { + if (!SetWindowPos(hwnd_, nullptr, DipToPixel(rect.left), DipToPixel(rect.top), + DipToPixel(rect.GetRight()), DipToPixel(rect.GetBottom()), + SWP_NOZORDER)) + throw Win32Error(::GetLastError(), "Failed to invoke SetWindowPos."); +} + +Point WinNativeWindow::GetMousePosition() { + POINT p; + if (!::GetCursorPos(&p)) + throw Win32Error(::GetLastError(), "Failed to get cursor position."); + if (!::ScreenToClient(hwnd_, &p)) + throw Win32Error(::GetLastError(), "Failed to call ScreenToClient."); + return PixelToDip(p); +} + +bool WinNativeWindow::CaptureMouse() { + ::SetCapture(hwnd_); + return true; +} + +bool WinNativeWindow::ReleaseMouse() { + const auto result = ::ReleaseCapture(); + return result != 0; +} + +void WinNativeWindow::RequestRepaint() { + log::TagDebug(log_tag, u"A repaint is requested."); + if (!::InvalidateRect(hwnd_, nullptr, FALSE)) + throw Win32Error(::GetLastError(), "Failed to invalidate window."); + if (!::UpdateWindow(hwnd_)) + throw Win32Error(::GetLastError(), "Failed to update window."); +} + +std::unique_ptr WinNativeWindow::BeginPaint() { + return std::make_unique( + window_render_target_.get()); +} + +void WinNativeWindow::SetCursor(std::shared_ptr cursor) { + if (cursor == nullptr) { + throw std::runtime_error("Can't use a nullptr as cursor."); + } + + cursor_ = CheckPlatform(cursor, GetPlatformId()); + + if (!::SetClassLongPtrW(hwnd_, GCLP_HCURSOR, + reinterpret_cast(cursor_->GetHandle()))) { + log::TagWarn(log_tag, + u"Failed to set cursor because failed to set class long. Last " + u"error code: {}.", + ::GetLastError()); + return; + } + + if (!IsVisible()) return; + + auto lg = [](const std::u16string_view& reason) { + log::TagWarn( + log_tag, + u"Failed to set cursor because {} when window is visible. (We need to " + u"update cursor if it is inside the window.) Last error code: {}.", + reason, ::GetLastError()); + }; + + ::POINT point; + if (!::GetCursorPos(&point)) { + lg(u"failed to get cursor pos"); + return; + } + + ::RECT rect; + if (!::GetClientRect(hwnd_, &rect)) { + lg(u"failed to get window's client rect"); + return; + } + + ::POINT lefttop{rect.left, rect.top}; + ::POINT rightbottom{rect.right, rect.bottom}; + if (!::ClientToScreen(hwnd_, &lefttop)) { + lg(u"failed to call ClientToScreen on lefttop"); + return; + } + + if (!::ClientToScreen(hwnd_, &rightbottom)) { + lg(u"failed to call ClientToScreen on rightbottom"); + return; + } + + if (point.x >= lefttop.x && point.y >= lefttop.y && + point.x <= rightbottom.x && point.y <= rightbottom.y) { + ::SetCursor(cursor_->GetHandle()); + } +} + +IInputMethodContext* WinNativeWindow::GetInputMethodContext() { + return static_cast(input_method_context_.get()); +} + +bool WinNativeWindow::HandleNativeWindowMessage(HWND hwnd, UINT msg, + WPARAM w_param, LPARAM l_param, + LRESULT* result) { + WindowNativeMessageEventArgs args{ + WindowNativeMessage{hwnd, msg, w_param, l_param}}; + native_message_event_.Raise(args); + if (args.IsHandled()) { + *result = args.GetResult(); + return true; + } + + switch (msg) { + case WM_PAINT: + OnPaintInternal(); + *result = 0; + return true; + case WM_ERASEBKGND: + *result = 1; + return true; + case WM_SETFOCUS: + OnSetFocusInternal(); + *result = 0; + return true; + case WM_KILLFOCUS: + OnKillFocusInternal(); + *result = 0; + return true; + case WM_MOUSEMOVE: { + POINT point; + point.x = GET_X_LPARAM(l_param); + point.y = GET_Y_LPARAM(l_param); + OnMouseMoveInternal(point); + *result = 0; + return true; + } + case WM_LBUTTONDOWN: { + POINT point; + point.x = GET_X_LPARAM(l_param); + point.y = GET_Y_LPARAM(l_param); + OnMouseDownInternal(platform::gui::mouse_buttons::left, point); + *result = 0; + return true; + } + case WM_LBUTTONUP: { + POINT point; + point.x = GET_X_LPARAM(l_param); + point.y = GET_Y_LPARAM(l_param); + OnMouseUpInternal(platform::gui::mouse_buttons::left, point); + *result = 0; + return true; + } + case WM_RBUTTONDOWN: { + POINT point; + point.x = GET_X_LPARAM(l_param); + point.y = GET_Y_LPARAM(l_param); + OnMouseDownInternal(platform::gui::mouse_buttons::right, point); + *result = 0; + return true; + } + case WM_RBUTTONUP: { + POINT point; + point.x = GET_X_LPARAM(l_param); + point.y = GET_Y_LPARAM(l_param); + OnMouseUpInternal(platform::gui::mouse_buttons::right, point); + *result = 0; + return true; + } + case WM_MBUTTONDOWN: { + POINT point; + point.x = GET_X_LPARAM(l_param); + point.y = GET_Y_LPARAM(l_param); + OnMouseDownInternal(platform::gui::mouse_buttons::middle, point); + *result = 0; + return true; + } + case WM_MBUTTONUP: { + POINT point; + point.x = GET_X_LPARAM(l_param); + point.y = GET_Y_LPARAM(l_param); + OnMouseUpInternal(platform::gui::mouse_buttons::middle, point); + *result = 0; + return true; + } + case WM_MOUSEWHEEL: + POINT point; + point.x = GET_X_LPARAM(l_param); + point.y = GET_Y_LPARAM(l_param); + ScreenToClient(hwnd, &point); + OnMouseWheelInternal(GET_WHEEL_DELTA_WPARAM(w_param), point); + *result = 0; + return true; + case WM_KEYDOWN: + OnKeyDownInternal(static_cast(w_param)); + *result = 0; + return true; + case WM_KEYUP: + OnKeyUpInternal(static_cast(w_param)); + *result = 0; + return true; + case WM_SYSKEYDOWN: + if (l_param & (1 << 29)) { + OnKeyDownInternal(static_cast(w_param)); + *result = 0; + return true; + } + return false; + case WM_SYSKEYUP: + if (l_param & (1 << 29)) { + OnKeyUpInternal(static_cast(w_param)); + *result = 0; + return true; + } + return false; + case WM_SIZE: + OnResizeInternal(LOWORD(l_param), HIWORD(l_param)); + *result = 0; + return true; + case WM_ACTIVATE: + if (w_param == WA_ACTIVE || w_param == WA_CLICKACTIVE) + OnActivatedInternal(); + else if (w_param == WA_INACTIVE) + OnDeactivatedInternal(); + *result = 0; + return true; + case WM_DESTROY: + OnDestroyInternal(); + *result = 0; + return true; + case WM_IME_SETCONTEXT: + l_param &= ~ISC_SHOWUICOMPOSITIONWINDOW; + *result = ::DefWindowProcW(hwnd, msg, w_param, l_param); + return true; + // We must block these message from DefWindowProc or it will create + // an ugly composition window. + case WM_IME_STARTCOMPOSITION: + case WM_IME_COMPOSITION: + *result = 0; + return true; + case WM_DPICHANGED: { + dpi_ = static_cast(LOWORD(w_param)); + const RECT* suggest_rect = reinterpret_cast(l_param); + window_render_target_->SetDpi(dpi_, dpi_); + SetWindowPos(hwnd_, NULL, suggest_rect->left, suggest_rect->top, + suggest_rect->right - suggest_rect->left, + suggest_rect->bottom - suggest_rect->top, + SWP_NOZORDER | SWP_NOACTIVATE); + } + default: + return false; + } +} + +RECT WinNativeWindow::GetClientRectPixel() { + RECT rect; + if (!GetClientRect(hwnd_, &rect)) + throw Win32Error(::GetLastError(), "Failed to invoke GetClientRect."); + return rect; +} + +void WinNativeWindow::OnDestroyInternal() { + application_->GetWindowManager()->UnregisterWindow(hwnd_); + hwnd_ = nullptr; + destroy_event_.Raise(nullptr); + if (!sync_flag_) { + sync_flag_ = true; + delete this; + } +} + +void WinNativeWindow::OnPaintInternal() { + paint_event_.Raise(nullptr); + ValidateRect(hwnd_, nullptr); + log::TagDebug(log_tag, u"A repaint is finished."); +} + +void WinNativeWindow::OnResizeInternal(const int new_width, + const int new_height) { + if (!(new_width == 0 && new_height == 0)) { + window_render_target_->ResizeBuffer(new_width, new_height); + resize_event_.Raise(Size{PixelToDip(new_width), PixelToDip(new_height)}); + } +} + +void WinNativeWindow::OnSetFocusInternal() { + has_focus_ = true; + focus_event_.Raise(FocusChangeType::Gain); +} + +void WinNativeWindow::OnKillFocusInternal() { + has_focus_ = false; + focus_event_.Raise(FocusChangeType::Lost); +} + +void WinNativeWindow::OnMouseMoveInternal(const POINT point) { + // when mouse was previous outside the window + if (!is_mouse_in_) { + // invoke TrackMouseEvent to have WM_MOUSELEAVE sent. + TRACKMOUSEEVENT tme; + tme.cbSize = sizeof tme; + tme.dwFlags = TME_LEAVE; + tme.hwndTrack = hwnd_; + + TrackMouseEvent(&tme); + + is_mouse_in_ = true; + mouse_enter_leave_event_.Raise(MouseEnterLeaveType::Enter); + } + + mouse_move_event_.Raise(PixelToDip(point)); +} + +void WinNativeWindow::OnMouseLeaveInternal() { + is_mouse_in_ = false; + mouse_enter_leave_event_.Raise(MouseEnterLeaveType::Leave); +} + +void WinNativeWindow::OnMouseDownInternal(platform::gui::MouseButton button, + POINT point) { + const auto dip_point = PixelToDip(point); + mouse_down_event_.Raise({button, dip_point, RetrieveKeyMofifier()}); +} + +void WinNativeWindow::OnMouseUpInternal(platform::gui::MouseButton button, + POINT point) { + const auto dip_point = PixelToDip(point); + mouse_up_event_.Raise({button, dip_point, RetrieveKeyMofifier()}); +} + +void WinNativeWindow::OnMouseWheelInternal(short delta, POINT point) { + CRU_UNUSED(delta) + CRU_UNUSED(point) +} + +void WinNativeWindow::OnKeyDownInternal(int virtual_code) { + key_down_event_.Raise( + {VirtualKeyToKeyCode(virtual_code), RetrieveKeyMofifier()}); +} + +void WinNativeWindow::OnKeyUpInternal(int virtual_code) { + key_up_event_.Raise( + {VirtualKeyToKeyCode(virtual_code), RetrieveKeyMofifier()}); +} + +void WinNativeWindow::OnActivatedInternal() {} + +void WinNativeWindow::OnDeactivatedInternal() {} +} // namespace cru::platform::gui::win diff --git a/src/win/gui/WindowClass.cpp b/src/win/gui/WindowClass.cpp new file mode 100644 index 00000000..a033d091 --- /dev/null +++ b/src/win/gui/WindowClass.cpp @@ -0,0 +1,28 @@ +#include "cru/win/gui/WindowClass.hpp" + +#include "cru/win/gui/Exception.hpp" + +namespace cru::platform::gui::win { +WindowClass::WindowClass(std::wstring name, WNDPROC window_proc, + HINSTANCE h_instance) + : name_(std::move(name)) { + WNDCLASSEXW window_class; + window_class.cbSize = sizeof(WNDCLASSEXW); + + window_class.style = CS_HREDRAW | CS_VREDRAW; + window_class.lpfnWndProc = window_proc; + window_class.cbClsExtra = 0; + window_class.cbWndExtra = 0; + window_class.hInstance = h_instance; + window_class.hIcon = LoadIcon(NULL, IDI_APPLICATION); + window_class.hCursor = LoadCursor(NULL, IDC_ARROW); + window_class.hbrBackground = GetSysColorBrush(COLOR_BTNFACE); + window_class.lpszMenuName = NULL; + window_class.lpszClassName = name_.c_str(); + window_class.hIconSm = NULL; + + atom_ = ::RegisterClassExW(&window_class); + if (atom_ == 0) + throw Win32Error(::GetLastError(), "Failed to create window class."); +} +} // namespace cru::platform::gui::win diff --git a/src/win/gui/WindowManager.cpp b/src/win/gui/WindowManager.cpp new file mode 100644 index 00000000..4e84e967 --- /dev/null +++ b/src/win/gui/WindowManager.cpp @@ -0,0 +1,56 @@ +#include "WindowManager.hpp" + +#include "cru/win/gui/UiApplication.hpp" +#include "cru/win/gui/Window.hpp" +#include "cru/win/gui/WindowClass.hpp" + +namespace cru::platform::gui::win { +LRESULT __stdcall GeneralWndProc(HWND hWnd, UINT Msg, WPARAM wParam, + LPARAM lParam) { + auto window = + WinUiApplication::GetInstance()->GetWindowManager()->FromHandle(hWnd); + + LRESULT result; + if (window != nullptr && + window->HandleNativeWindowMessage(hWnd, Msg, wParam, lParam, &result)) + return result; + + return DefWindowProc(hWnd, Msg, wParam, lParam); +} + +WindowManager::WindowManager(WinUiApplication* application) { + application_ = application; + general_window_class_ = std::make_unique( + L"CruUIWindowClass", GeneralWndProc, application->GetInstanceHandle()); +} + +WindowManager::~WindowManager() { + for (const auto& [key, window] : window_map_) delete window; +} + +void WindowManager::RegisterWindow(HWND hwnd, WinNativeWindow* window) { + Expects(window_map_.count(hwnd) == 0); // The hwnd is already in the map. + window_map_.emplace(hwnd, window); +} + +void WindowManager::UnregisterWindow(HWND hwnd) { + const auto find_result = window_map_.find(hwnd); + Expects(find_result != window_map_.end()); // The hwnd is not in the map. + window_map_.erase(find_result); + if (window_map_.empty()) application_->RequestQuit(0); +} + +WinNativeWindow* WindowManager::FromHandle(HWND hwnd) { + const auto find_result = window_map_.find(hwnd); + if (find_result == window_map_.end()) + return nullptr; + else + return find_result->second; +} + +std::vector WindowManager::GetAllWindows() const { + std::vector windows; + for (const auto& [key, value] : window_map_) windows.push_back(value); + return windows; +} +} // namespace cru::platform::gui::win diff --git a/src/win/gui/WindowManager.hpp b/src/win/gui/WindowManager.hpp new file mode 100644 index 00000000..3b037f89 --- /dev/null +++ b/src/win/gui/WindowManager.hpp @@ -0,0 +1,51 @@ +#pragma once +#include "cru/win/WinPreConfig.hpp" + +#include "cru/common/Base.hpp" + +#include +#include +#include + +namespace cru::platform::gui::win { +class WinUiApplication; +class WinNativeWindow; +class WindowClass; + +class WindowManager : public Object { + public: + WindowManager(WinUiApplication* application); + + CRU_DELETE_COPY(WindowManager) + CRU_DELETE_MOVE(WindowManager) + + ~WindowManager() override; + + // Get the general window class for creating ordinary window. + WindowClass* GetGeneralWindowClass() const { + return general_window_class_.get(); + } + + // Register a window newly created. + // This function adds the hwnd to hwnd-window map. + // It should be called immediately after a window was created. + void RegisterWindow(HWND hwnd, WinNativeWindow* window); + + // Unregister a window that is going to be destroyed. + // This function removes the hwnd from the hwnd-window map. + // It should be called immediately before a window is going to be destroyed, + void UnregisterWindow(HWND hwnd); + + // Return a pointer to the Window object related to the HWND or nullptr if the + // hwnd is not in the map. + WinNativeWindow* FromHandle(HWND hwnd); + + std::vector GetAllWindows() const; + + private: + WinUiApplication* application_; + + std::unique_ptr general_window_class_; + std::map window_map_; +}; +} // namespace cru::platform::gui::win diff --git a/src/win/native/CMakeLists.txt b/src/win/native/CMakeLists.txt deleted file mode 100644 index 4b84600b..00000000 --- a/src/win/native/CMakeLists.txt +++ /dev/null @@ -1,31 +0,0 @@ -set(CRU_WIN_NATIVE_INCLUDE_DIR ${CRU_INCLUDE_DIR}/cru/win/native) - -add_library(cru_win_native STATIC - TimerManager.hpp - WindowManager.hpp - - Cursor.cpp - GodWindow.cpp - InputMethod.cpp - Keyboard.cpp - TimerManager.cpp - UiApplication.cpp - Window.cpp - WindowClass.cpp - WindowManager.cpp -) -target_sources(cru_win_native PUBLIC - ${CRU_WIN_NATIVE_INCLUDE_DIR}/Cursor.hpp - ${CRU_WIN_NATIVE_INCLUDE_DIR}/Exception.hpp - ${CRU_WIN_NATIVE_INCLUDE_DIR}/Base.hpp - ${CRU_WIN_NATIVE_INCLUDE_DIR}/GodWindow.hpp - ${CRU_WIN_NATIVE_INCLUDE_DIR}/InputMethod.hpp - ${CRU_WIN_NATIVE_INCLUDE_DIR}/Keyboard.hpp - ${CRU_WIN_NATIVE_INCLUDE_DIR}/Resource.hpp - ${CRU_WIN_NATIVE_INCLUDE_DIR}/UiApplication.hpp - ${CRU_WIN_NATIVE_INCLUDE_DIR}/Window.hpp - ${CRU_WIN_NATIVE_INCLUDE_DIR}/WindowClass.hpp - ${CRU_WIN_NATIVE_INCLUDE_DIR}/WindowNativeMessageEventArgs.hpp -) -target_link_libraries(cru_win_native PUBLIC imm32) -target_link_libraries(cru_win_native PUBLIC cru_win_graph_direct cru_platform_native) diff --git a/src/win/native/Cursor.cpp b/src/win/native/Cursor.cpp deleted file mode 100644 index 429f6e7c..00000000 --- a/src/win/native/Cursor.cpp +++ /dev/null @@ -1,51 +0,0 @@ -#include "cru/win/native/Cursor.hpp" - -#include "cru/common/Logger.hpp" -#include "cru/win/native/Exception.hpp" - -#include - -namespace cru::platform::native::win { -WinCursor::WinCursor(HCURSOR handle, bool auto_destroy) { - handle_ = handle; - auto_destroy_ = auto_destroy; -} - -WinCursor::~WinCursor() { - if (auto_destroy_) { - if (!::DestroyCursor(handle_)) { - // This is not a fetal error but might still need notice because it may - // cause leak. - log::TagWarn(log_tag, u"Failed to destroy a cursor. Last error code: {}", - ::GetLastError()); - } - } -} - -namespace { -WinCursor* LoadWinCursor(const wchar_t* name) { - const auto handle = static_cast(::LoadImageW( - NULL, name, IMAGE_CURSOR, SM_CYCURSOR, SM_CYCURSOR, LR_SHARED)); - if (handle == NULL) { - throw Win32Error(::GetLastError(), "Failed to load system cursor."); - } - return new WinCursor(handle, false); -} -} // namespace - -WinCursorManager::WinCursorManager() - : sys_arrow_(LoadWinCursor(IDC_ARROW)), - sys_hand_(LoadWinCursor(IDC_HAND)) {} - -std::shared_ptr WinCursorManager::GetSystemWinCursor( - SystemCursorType type) { - switch (type) { - case SystemCursorType::Arrow: - return sys_arrow_; - case SystemCursorType::Hand: - return sys_hand_; - default: - throw std::runtime_error("Unknown system cursor value."); - } -} -} // namespace cru::platform::native::win diff --git a/src/win/native/GodWindow.cpp b/src/win/native/GodWindow.cpp deleted file mode 100644 index 799a3cc6..00000000 --- a/src/win/native/GodWindow.cpp +++ /dev/null @@ -1,63 +0,0 @@ -#include "cru/win/native/GodWindow.hpp" - -#include "cru/common/Logger.hpp" -#include "cru/win/native/Exception.hpp" -#include "cru/win/native/UiApplication.hpp" -#include "cru/win/native/WindowClass.hpp" - -namespace cru::platform::native::win { -constexpr auto god_window_class_name = L"GodWindowClass"; - -LRESULT CALLBACK GodWndProc(HWND hWnd, UINT uMsg, WPARAM wParam, - LPARAM lParam) { - const auto app = WinUiApplication::GetInstance(); - - if (app) { - LRESULT result; - auto god_window = app->GetGodWindow(); - if (god_window != nullptr) { - const auto handled = god_window->HandleGodWindowMessage( - hWnd, uMsg, wParam, lParam, &result); - if (handled) return result; - } - } - return DefWindowProcW(hWnd, uMsg, wParam, lParam); -} - -GodWindow::GodWindow(WinUiApplication* application) { - application_ = application; - - const auto h_instance = application->GetInstanceHandle(); - - god_window_class_ = std::make_unique(god_window_class_name, - GodWndProc, h_instance); - - hwnd_ = CreateWindowEx(0, god_window_class_name, L"", 0, CW_USEDEFAULT, - CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, - HWND_MESSAGE, nullptr, h_instance, nullptr); - - if (hwnd_ == nullptr) - throw Win32Error(::GetLastError(), "Failed to create god window."); -} - -GodWindow::~GodWindow() { - if (!::DestroyWindow(hwnd_)) { - // Although this could be "safely" ignore. - log::TagWarn(log_tag, u"Failed to destroy god window."); - } -} - -bool GodWindow::HandleGodWindowMessage(HWND hwnd, UINT msg, WPARAM w_param, - LPARAM l_param, LRESULT* result) { - WindowNativeMessageEventArgs args( - WindowNativeMessage{hwnd, msg, w_param, l_param}); - message_event_.Raise(args); - - if (args.IsHandled()) { - *result = args.GetResult(); - return true; - } - - return false; -} -} // namespace cru::platform::native::win diff --git a/src/win/native/InputMethod.cpp b/src/win/native/InputMethod.cpp deleted file mode 100644 index 45c5f8da..00000000 --- a/src/win/native/InputMethod.cpp +++ /dev/null @@ -1,278 +0,0 @@ -#include "cru/win/native/InputMethod.hpp" - -#include "cru/common/Logger.hpp" -#include "cru/common/StringUtil.hpp" -#include "cru/platform/Check.hpp" -#include "cru/win/Exception.hpp" -#include "cru/win/native/Window.hpp" - -#include - -namespace cru::platform::native::win { -AutoHIMC::AutoHIMC(HWND hwnd) : hwnd_(hwnd) { - Expects(hwnd); - handle_ = ::ImmGetContext(hwnd); -} - -AutoHIMC::AutoHIMC(AutoHIMC&& other) - : hwnd_(other.hwnd_), handle_(other.handle_) { - other.hwnd_ = nullptr; - other.handle_ = nullptr; -} - -AutoHIMC& AutoHIMC::operator=(AutoHIMC&& other) { - if (this != &other) { - Object::operator=(std::move(other)); - this->hwnd_ = other.hwnd_; - this->handle_ = other.handle_; - other.hwnd_ = nullptr; - other.handle_ = nullptr; - } - return *this; -} - -AutoHIMC::~AutoHIMC() { - if (handle_) { - if (!::ImmReleaseContext(hwnd_, handle_)) - log::TagWarn(log_tag, u"Failed to release HIMC."); - } -} - -// copied from chromium -namespace { -// Determines whether or not the given attribute represents a target -// (a.k.a. a selection). -bool IsTargetAttribute(char attribute) { - return (attribute == ATTR_TARGET_CONVERTED || - attribute == ATTR_TARGET_NOTCONVERTED); -} -// Helper function for ImeInput::GetCompositionInfo() method, to get the target -// range that's selected by the user in the current composition string. -void GetCompositionTargetRange(HIMC imm_context, int* target_start, - int* target_end) { - int attribute_size = - ::ImmGetCompositionString(imm_context, GCS_COMPATTR, NULL, 0); - if (attribute_size > 0) { - int start = 0; - int end = 0; - std::vector attribute_data(attribute_size); - ::ImmGetCompositionString(imm_context, GCS_COMPATTR, attribute_data.data(), - attribute_size); - for (start = 0; start < attribute_size; ++start) { - if (IsTargetAttribute(attribute_data[start])) break; - } - for (end = start; end < attribute_size; ++end) { - if (!IsTargetAttribute(attribute_data[end])) break; - } - if (start == attribute_size) { - // This composition clause does not contain any target clauses, - // i.e. this clauses is an input clause. - // We treat the whole composition as a target clause. - start = 0; - end = attribute_size; - } - *target_start = start; - *target_end = end; - } -} -// Helper function for ImeInput::GetCompositionInfo() method, to get underlines -// information of the current composition string. -CompositionClauses GetCompositionClauses(HIMC imm_context, int target_start, - int target_end) { - CompositionClauses result; - int clause_size = - ::ImmGetCompositionString(imm_context, GCS_COMPCLAUSE, NULL, 0); - int clause_length = clause_size / sizeof(std::uint32_t); - if (clause_length) { - result.reserve(clause_length - 1); - std::vector clause_data(clause_length); - ::ImmGetCompositionString(imm_context, GCS_COMPCLAUSE, clause_data.data(), - clause_size); - for (int i = 0; i < clause_length - 1; ++i) { - CompositionClause clause; - clause.start = clause_data[i]; - clause.end = clause_data[i + 1]; - clause.target = false; - // Use thick underline for the target clause. - if (clause.start >= target_start && clause.end <= target_end) { - clause.target = true; - } - result.push_back(clause); - } - } - return result; -} - -std::u16string GetString(HIMC imm_context) { - LONG string_size = - ::ImmGetCompositionString(imm_context, GCS_COMPSTR, NULL, 0); - std::u16string result((string_size / sizeof(char16_t)), 0); - ::ImmGetCompositionString(imm_context, GCS_COMPSTR, result.data(), - string_size); - return result; -} - -std::u16string GetResultString(HIMC imm_context) { - LONG string_size = - ::ImmGetCompositionString(imm_context, GCS_RESULTSTR, NULL, 0); - std::u16string result((string_size / sizeof(char16_t)), 0); - ::ImmGetCompositionString(imm_context, GCS_RESULTSTR, result.data(), - string_size); - return result; -} - -CompositionText GetCompositionInfo(HIMC imm_context) { - // We only care about GCS_COMPATTR, GCS_COMPCLAUSE and GCS_CURSORPOS, and - // convert them into underlines and selection range respectively. - - auto text = GetString(imm_context); - - int length = static_cast(text.length()); - // Find out the range selected by the user. - int target_start = length; - int target_end = length; - GetCompositionTargetRange(imm_context, &target_start, &target_end); - - auto clauses = GetCompositionClauses(imm_context, target_start, target_end); - - int cursor = ::ImmGetCompositionString(imm_context, GCS_CURSORPOS, NULL, 0); - - return CompositionText{std::move(text), std::move(clauses), - TextRange{cursor}}; -} - -} // namespace - -WinInputMethodContext::WinInputMethodContext( - gsl::not_null window) - : native_window_(window) { - event_guard_ += window->NativeMessageEvent()->AddHandler( - std::bind(&WinInputMethodContext::OnWindowNativeMessage, this, - std::placeholders::_1)); -} - -WinInputMethodContext::~WinInputMethodContext() {} - -void WinInputMethodContext::EnableIME() { - const auto hwnd = native_window_->GetWindowHandle(); - if (::ImmAssociateContextEx(hwnd, nullptr, IACE_DEFAULT) == FALSE) { - log::TagWarn(log_tag, u"Failed to enable ime."); - } -} - -void WinInputMethodContext::DisableIME() { - const auto hwnd = native_window_->GetWindowHandle(); - AutoHIMC himc{hwnd}; - - if (!::ImmNotifyIME(himc.Get(), NI_COMPOSITIONSTR, CPS_COMPLETE, 0)) { - log::TagWarn(log_tag, - u"Failed to complete composition before disable ime."); - } - - if (::ImmAssociateContextEx(hwnd, nullptr, 0) == FALSE) { - log::TagWarn(log_tag, u"Failed to disable ime."); - } -} - -void WinInputMethodContext::CompleteComposition() { - auto himc = GetHIMC(); - if (!::ImmNotifyIME(himc.Get(), NI_COMPOSITIONSTR, CPS_COMPLETE, 0)) { - log::TagWarn(log_tag, u"Failed to complete composition."); - } -} - -void WinInputMethodContext::CancelComposition() { - auto himc = GetHIMC(); - if (!::ImmNotifyIME(himc.Get(), NI_COMPOSITIONSTR, CPS_CANCEL, 0)) { - log::TagWarn(log_tag, u"Failed to complete composition."); - } -} - -CompositionText WinInputMethodContext::GetCompositionText() { - auto himc = GetHIMC(); - return GetCompositionInfo(himc.Get()); -} - -void WinInputMethodContext::SetCandidateWindowPosition(const Point& point) { - auto himc = GetHIMC(); - - ::CANDIDATEFORM form; - form.dwIndex = 1; - form.dwStyle = CFS_CANDIDATEPOS; - - form.ptCurrentPos = native_window_->DipToPixel(point); - - if (!::ImmSetCandidateWindow(himc.Get(), &form)) - log::TagDebug(log_tag, - u"Failed to set input method candidate window position."); -} - -IEvent* WinInputMethodContext::CompositionStartEvent() { - return &composition_start_event_; -} - -IEvent* WinInputMethodContext::CompositionEndEvent() { - return &composition_end_event_; -}; - -IEvent* WinInputMethodContext::CompositionEvent() { - return &composition_event_; -} - -IEvent* WinInputMethodContext::TextEvent() { - return &text_event_; -} - -void WinInputMethodContext::OnWindowNativeMessage( - WindowNativeMessageEventArgs& args) { - const auto& message = args.GetWindowMessage(); - switch (message.msg) { - case WM_CHAR: { - const auto c = static_cast(message.w_param); - if (IsUtf16SurrogatePairCodeUnit(c)) { - // I don't think this will happen because normal key strike without ime - // should only trigger ascci character. If it is a charater from - // supplementary planes, it should be handled with ime messages. - log::TagWarn(log_tag, - u"A WM_CHAR message for character from supplementary " - u"planes is ignored."); - } else { - char16_t s[1] = {c}; - text_event_.Raise({s, 1}); - } - args.HandleWithResult(0); - break; - } - case WM_IME_COMPOSITION: { - composition_event_.Raise(nullptr); - auto composition_text = GetCompositionText(); - log::TagDebug(log_tag, u"WM_IME_COMPOSITION composition text:\n{}", - composition_text); - if (message.l_param & GCS_RESULTSTR) { - auto result_string = GetResultString(); - text_event_.Raise(result_string); - } - break; - } - case WM_IME_STARTCOMPOSITION: { - composition_start_event_.Raise(nullptr); - break; - } - case WM_IME_ENDCOMPOSITION: { - composition_end_event_.Raise(nullptr); - break; - } - } -} - -std::u16string WinInputMethodContext::GetResultString() { - auto himc = GetHIMC(); - auto result = win::GetResultString(himc.Get()); - return result; -} - -AutoHIMC WinInputMethodContext::GetHIMC() { - const auto hwnd = native_window_->GetWindowHandle(); - return AutoHIMC{hwnd}; -} -} // namespace cru::platform::native::win diff --git a/src/win/native/Keyboard.cpp b/src/win/native/Keyboard.cpp deleted file mode 100644 index 929ca737..00000000 --- a/src/win/native/Keyboard.cpp +++ /dev/null @@ -1,74 +0,0 @@ -#include "cru/win/native/Keyboard.hpp" - -namespace cru::platform::native::win { -KeyCode VirtualKeyToKeyCode(int virtual_key) { - if (virtual_key >= 0x30 && virtual_key <= 0x39) { - return KeyCode{static_cast(KeyCode::N0) + (virtual_key - 0x30)}; - } else if (virtual_key >= 0x41 && virtual_key <= 0x5a) { - return KeyCode{static_cast(KeyCode::A) + (virtual_key - 0x41)}; - } else if (virtual_key >= VK_NUMPAD0 && virtual_key <= VK_NUMPAD9) { - return KeyCode{static_cast(KeyCode::NumPad0) + - (virtual_key - VK_NUMPAD0)}; - } else if (virtual_key >= VK_F1 && virtual_key <= VK_F12) { - return KeyCode{static_cast(KeyCode::F1) + (virtual_key - VK_F1)}; - } else { - switch (virtual_key) { -#define CRU_MAP_KEY(virtual_key, keycode) \ - case virtual_key: \ - return KeyCode::keycode; - - CRU_MAP_KEY(VK_LBUTTON, LeftButton) - CRU_MAP_KEY(VK_MBUTTON, MiddleButton) - CRU_MAP_KEY(VK_RBUTTON, RightButton) - CRU_MAP_KEY(VK_ESCAPE, Escape) - CRU_MAP_KEY(VK_OEM_3, GraveAccent) - CRU_MAP_KEY(VK_TAB, Tab) - CRU_MAP_KEY(VK_CAPITAL, CapsLock) - CRU_MAP_KEY(VK_LSHIFT, LeftShift) - CRU_MAP_KEY(VK_LCONTROL, LeftCtrl) - CRU_MAP_KEY(VK_LWIN, LeftSuper) - CRU_MAP_KEY(VK_LMENU, LeftAlt) - CRU_MAP_KEY(VK_OEM_MINUS, Minus) - CRU_MAP_KEY(VK_OEM_PLUS, Equal) - CRU_MAP_KEY(VK_BACK, Backspace) - CRU_MAP_KEY(VK_OEM_4, LeftSquareBracket) - CRU_MAP_KEY(VK_OEM_6, RightSquareBracket) - CRU_MAP_KEY(VK_OEM_5, BackSlash) - CRU_MAP_KEY(VK_OEM_1, Semicolon) - CRU_MAP_KEY(VK_OEM_7, Quote) - CRU_MAP_KEY(VK_OEM_COMMA, Comma) - CRU_MAP_KEY(VK_OEM_PERIOD, Period) - CRU_MAP_KEY(VK_OEM_2, Slash) - CRU_MAP_KEY(VK_RSHIFT, RightShift) - CRU_MAP_KEY(VK_RCONTROL, RightCtrl) - CRU_MAP_KEY(VK_RWIN, RightSuper) - CRU_MAP_KEY(VK_RMENU, RightAlt) - CRU_MAP_KEY(VK_INSERT, Insert) - CRU_MAP_KEY(VK_DELETE, Delete) - CRU_MAP_KEY(VK_HOME, Home) - CRU_MAP_KEY(VK_END, End) - CRU_MAP_KEY(VK_PRIOR, PageUp) - CRU_MAP_KEY(VK_NEXT, PageDown) - CRU_MAP_KEY(VK_UP, Up) - CRU_MAP_KEY(VK_LEFT, Left) - CRU_MAP_KEY(VK_DOWN, Down) - CRU_MAP_KEY(VK_RIGHT, Right) - CRU_MAP_KEY(VK_SNAPSHOT, PrintScreen) - CRU_MAP_KEY(VK_PAUSE, Pause) - -#undef CRU_MAP_KEY - - default: - return KeyCode::Unknown; - } - } -} - -KeyModifier RetrieveKeyMofifier() { - KeyModifier result{0}; - if (::GetKeyState(VK_SHIFT) < 0) result |= KeyModifiers::shift; - if (::GetKeyState(VK_CONTROL) < 0) result |= KeyModifiers::ctrl; - if (::GetKeyState(VK_MENU) < 0) result |= KeyModifiers::alt; - return result; -} -} // namespace cru::platform::native::win diff --git a/src/win/native/TimerManager.cpp b/src/win/native/TimerManager.cpp deleted file mode 100644 index 206ae3e3..00000000 --- a/src/win/native/TimerManager.cpp +++ /dev/null @@ -1,100 +0,0 @@ -#include "TimerManager.hpp" - -#include "cru/win/native/Base.hpp" -#include "cru/win/native/Exception.hpp" -#include "gsl/gsl_util" - -#include -#include - -namespace cru::platform::native::win { -constexpr int kSetImmediateWindowMessageId = WM_USER + 2000; - -TimerManager::TimerManager(GodWindow* god_window) { - god_window_ = god_window; - event_guard_ += god_window->MessageEvent()->AddHandler(std::bind( - &TimerManager::HandleGodWindowMessage, this, std::placeholders::_1)); -} - -long long TimerManager::SetTimer(TimerType type, int period, - std::function action) { - auto id = next_id_++; - TimerInfo timer_info{id, type, type == TimerType::Immediate ? 0 : period, - std::move(action)}; - if (type == TimerType::Immediate) { - if (!::PostMessageW(god_window_->GetHandle(), kSetImmediateWindowMessageId, - gsl::narrow(id), 0)) { - throw Win32Error( - ::GetLastError(), - "Failed to post window message to god window for set immediate."); - } - } else { - CreateNativeTimer(&timer_info); - } - - info_map_.emplace(id, std::move(timer_info)); - return id; -} - -void TimerManager::CancelTimer(long long id) { - if (id <= 0) return; - auto find_result = this->info_map_.find(id); - if (find_result != info_map_.cend()) { - auto& info = find_result->second; - KillNativeTimer(&info); - this->info_map_.erase(find_result); - } -} - -void TimerManager::CreateNativeTimer(TimerInfo* info) { - info->native_timer_id = gsl::narrow(info->id); - ::SetTimer(god_window_->GetHandle(), info->native_timer_id, info->period, - nullptr); -} - -void TimerManager::KillNativeTimer(TimerInfo* info) { - if (info->native_timer_id == 0) return; - ::KillTimer(god_window_->GetHandle(), info->native_timer_id); - info->native_timer_id = 0; -} - -void TimerManager::HandleGodWindowMessage(WindowNativeMessageEventArgs& args) { - const auto& message = args.GetWindowMessage(); - - switch (message.msg) { - case kSetImmediateWindowMessageId: { - auto find_result = - this->info_map_.find(static_cast(message.w_param)); - if (find_result != info_map_.cend()) { - auto& info = find_result->second; - info.action(); - info_map_.erase(find_result); - } - args.SetResult(0); - args.SetHandled(true); - return; - } - case WM_TIMER: { - auto find_result = - this->info_map_.find(static_cast(message.w_param)); - if (find_result != info_map_.cend()) { - auto& info = find_result->second; - if (info.type == TimerType::Interval) { - info.action(); - args.SetResult(0); - args.SetHandled(true); - } else if (info.type == TimerType::Timeout) { - info.action(); - KillNativeTimer(&info); - info_map_.erase(find_result); - args.SetResult(0); - args.SetHandled(true); - } - } - return; - } - default: - return; - } -} -} // namespace cru::platform::native::win diff --git a/src/win/native/TimerManager.hpp b/src/win/native/TimerManager.hpp deleted file mode 100644 index f2731f60..00000000 --- a/src/win/native/TimerManager.hpp +++ /dev/null @@ -1,61 +0,0 @@ -#pragma once -#include "cru/common/Event.hpp" -#include "cru/win/WinPreConfig.hpp" - -#include "cru/common/Base.hpp" -#include "cru/win/native/GodWindow.hpp" -#include "cru/win/native/WindowNativeMessageEventArgs.hpp" - -#include -#include -#include -#include - -namespace cru::platform::native::win { -enum class TimerType { Immediate, Timeout, Interval }; - -struct TimerInfo { - TimerInfo(long long id, TimerType type, int period, - std::function action, UINT_PTR native_timer_id = 0) - : id(id), - type(type), - period(period), - action(std::move(action)), - native_timer_id(native_timer_id) {} - - long long id; - TimerType type; - int period; // in milliseconds - std::function action; - UINT_PTR native_timer_id; -}; - -class TimerManager : public Object { - public: - TimerManager(GodWindow* god_window); - - CRU_DELETE_COPY(TimerManager) - CRU_DELETE_MOVE(TimerManager) - - ~TimerManager() override = default; - - // Period is in milliseconds. When type is immediate, it is not checked and - // used. - long long SetTimer(TimerType type, int period, std::function action); - void CancelTimer(long long id); - - private: - void HandleGodWindowMessage(WindowNativeMessageEventArgs& args); - - void CreateNativeTimer(TimerInfo* info); - void KillNativeTimer(TimerInfo* info); - - private: - GodWindow* god_window_; - - EventRevokerListGuard event_guard_; - - long long next_id_ = 1; - std::unordered_map info_map_; -}; -} // namespace cru::platform::native::win diff --git a/src/win/native/UiApplication.cpp b/src/win/native/UiApplication.cpp deleted file mode 100644 index 87ef0b81..00000000 --- a/src/win/native/UiApplication.cpp +++ /dev/null @@ -1,118 +0,0 @@ -#include "cru/win/native/UiApplication.hpp" - -#include "../DebugLogger.hpp" -#include "../StdOutLogger.hpp" -#include "TimerManager.hpp" -#include "WindowManager.hpp" -#include "cru/common/Logger.hpp" -#include "cru/platform/Check.hpp" -#include "cru/win/graph/direct/Factory.hpp" -#include "cru/win/native/Cursor.hpp" -#include "cru/win/native/Exception.hpp" -#include "cru/win/native/GodWindow.hpp" -#include "cru/win/native/InputMethod.hpp" -#include "cru/win/native/Window.hpp" - -namespace cru::platform::native { -std::unique_ptr CreateUiApplication() { - return std::make_unique(); -} -} // namespace cru::platform::native - -namespace cru::platform::native::win { -WinUiApplication* WinUiApplication::instance = nullptr; - -WinUiApplication::WinUiApplication() { - instance = this; - - instance_handle_ = ::GetModuleHandleW(nullptr); - if (!instance_handle_) - throw Win32Error("Failed to get module(instance) handle."); - - ::SetThreadDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE); - - log::Logger::GetInstance()->AddSource( - std::make_unique<::cru::platform::win::WinDebugLoggerSource>()); - log::Logger::GetInstance()->AddSource( - std::make_unique<::cru::platform::win::WinStdOutLoggerSource>()); - - graph_factory_ = - std::make_unique(); - - god_window_ = std::make_unique(this); - timer_manager_ = std::make_unique(god_window_.get()); - window_manager_ = std::make_unique(this); - cursor_manager_ = std::make_unique(); -} - -WinUiApplication::~WinUiApplication() { instance = nullptr; } - -int WinUiApplication::Run() { - MSG msg; - while (GetMessageW(&msg, nullptr, 0, 0)) { - TranslateMessage(&msg); - DispatchMessageW(&msg); - } - - for (const auto& handler : quit_handlers_) handler(); - - return static_cast(msg.wParam); -} - -void WinUiApplication::RequestQuit(const int quit_code) { - ::PostQuitMessage(quit_code); -} - -void WinUiApplication::AddOnQuitHandler(std::function handler) { - quit_handlers_.push_back(std::move(handler)); -} - -long long WinUiApplication::SetImmediate(std::function action) { - return this->timer_manager_->SetTimer(TimerType::Immediate, 0, - std::move(action)); -} - -long long WinUiApplication::SetTimeout(std::chrono::milliseconds milliseconds, - std::function action) { - return this->timer_manager_->SetTimer(TimerType::Timeout, - gsl::narrow(milliseconds.count()), - std::move(action)); -} - -long long WinUiApplication::SetInterval(std::chrono::milliseconds milliseconds, - std::function action) { - return this->timer_manager_->SetTimer(TimerType::Interval, - gsl::narrow(milliseconds.count()), - std::move(action)); -} - -void WinUiApplication::CancelTimer(long long id) { - timer_manager_->CancelTimer(id); -} - -std::vector WinUiApplication::GetAllWindow() { - const auto&& windows = window_manager_->GetAllWindows(); - std::vector result; - for (const auto w : windows) { - result.push_back(static_cast(w)); - } - return result; -} - -INativeWindow* WinUiApplication::CreateWindow(INativeWindow* parent) { - WinNativeWindow* p = nullptr; - if (parent != nullptr) { - p = CheckPlatform(parent, GetPlatformId()); - } - return new WinNativeWindow(this, window_manager_->GetGeneralWindowClass(), - WS_OVERLAPPEDWINDOW, p); -} - -cru::platform::graph::IGraphFactory* WinUiApplication::GetGraphFactory() { - return graph_factory_.get(); -} - -ICursorManager* WinUiApplication::GetCursorManager() { - return cursor_manager_.get(); -} -} // namespace cru::platform::native::win diff --git a/src/win/native/Window.cpp b/src/win/native/Window.cpp deleted file mode 100644 index 1a6fcb07..00000000 --- a/src/win/native/Window.cpp +++ /dev/null @@ -1,453 +0,0 @@ -#include "cru/win/native/Window.hpp" - -#include "WindowManager.hpp" -#include "cru/common/Logger.hpp" -#include "cru/platform/Check.hpp" -#include "cru/platform/native/Base.hpp" -#include "cru/win/graph/direct/WindowPainter.hpp" -#include "cru/win/native/Cursor.hpp" -#include "cru/win/native/Exception.hpp" -#include "cru/win/native/InputMethod.hpp" -#include "cru/win/native/Keyboard.hpp" -#include "cru/win/native/UiApplication.hpp" -#include "cru/win/native/WindowClass.hpp" - -#include -#include -#include - -namespace cru::platform::native::win { -WinNativeWindow::WinNativeWindow(WinUiApplication* application, - WindowClass* window_class, DWORD window_style, - WinNativeWindow* parent) - : application_(application), parent_window_(parent) { - Expects(application); // application can't be null. - - if (parent != nullptr) { - throw new std::runtime_error("Can't use a invalid window as parent."); - } - - const auto window_manager = application->GetWindowManager(); - - hwnd_ = CreateWindowExW( - 0, window_class->GetName(), L"", window_style, CW_USEDEFAULT, - CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, - parent == nullptr ? nullptr : parent->GetWindowHandle(), nullptr, - application->GetInstanceHandle(), nullptr); - - if (hwnd_ == nullptr) - throw Win32Error(::GetLastError(), "Failed to create window."); - - auto dpi = ::GetDpiForWindow(hwnd_); - if (dpi == 0) - throw Win32Error(::GetLastError(), "Failed to get dpi of window."); - dpi_ = static_cast(dpi); - log::Debug(u"Dpi of window is {}.", dpi_); - - window_manager->RegisterWindow(hwnd_, this); - - SetCursor(application->GetCursorManager()->GetSystemCursor( - cru::platform::native::SystemCursorType::Arrow)); - - window_render_target_ = - std::make_unique( - application->GetDirectFactory(), hwnd_); - window_render_target_->SetDpi(dpi_, dpi_); - - input_method_context_ = std::make_unique(this); - input_method_context_->DisableIME(); -} - -WinNativeWindow::~WinNativeWindow() { - if (!sync_flag_) { - sync_flag_ = true; - Close(); - } -} - -void WinNativeWindow::Close() { ::DestroyWindow(hwnd_); } - -bool WinNativeWindow::IsVisible() { return ::IsWindowVisible(hwnd_); } - -void WinNativeWindow::SetVisible(bool is_visible) { - is_visible ? ShowWindow(hwnd_, SW_SHOWNORMAL) : ShowWindow(hwnd_, SW_HIDE); -} -Size WinNativeWindow::GetClientSize() { - const auto pixel_rect = GetClientRectPixel(); - return Size(PixelToDip(pixel_rect.right), PixelToDip(pixel_rect.bottom)); -} - -void WinNativeWindow::SetClientSize(const Size& size) { - const auto window_style = - static_cast(GetWindowLongPtr(hwnd_, GWL_STYLE)); - const auto window_ex_style = - static_cast(GetWindowLongPtr(hwnd_, GWL_EXSTYLE)); - - RECT rect; - rect.left = 0; - rect.top = 0; - rect.right = DipToPixel(size.width); - rect.bottom = DipToPixel(size.height); - if (!AdjustWindowRectEx(&rect, window_style, FALSE, window_ex_style)) - throw Win32Error(::GetLastError(), "Failed to invoke AdjustWindowRectEx."); - - if (!SetWindowPos(hwnd_, nullptr, 0, 0, rect.right - rect.left, - rect.bottom - rect.top, SWP_NOZORDER | SWP_NOMOVE)) - throw Win32Error(::GetLastError(), "Failed to invoke SetWindowPos."); -} - -Rect WinNativeWindow::GetWindowRect() { - RECT rect; - if (!::GetWindowRect(hwnd_, &rect)) - throw Win32Error(::GetLastError(), "Failed to invoke GetWindowRect."); - - return Rect::FromVertices(PixelToDip(rect.left), PixelToDip(rect.top), - PixelToDip(rect.right), PixelToDip(rect.bottom)); -} - -void WinNativeWindow::SetWindowRect(const Rect& rect) { - if (!SetWindowPos(hwnd_, nullptr, DipToPixel(rect.left), DipToPixel(rect.top), - DipToPixel(rect.GetRight()), DipToPixel(rect.GetBottom()), - SWP_NOZORDER)) - throw Win32Error(::GetLastError(), "Failed to invoke SetWindowPos."); -} - -Point WinNativeWindow::GetMousePosition() { - POINT p; - if (!::GetCursorPos(&p)) - throw Win32Error(::GetLastError(), "Failed to get cursor position."); - if (!::ScreenToClient(hwnd_, &p)) - throw Win32Error(::GetLastError(), "Failed to call ScreenToClient."); - return PixelToDip(p); -} - -bool WinNativeWindow::CaptureMouse() { - ::SetCapture(hwnd_); - return true; -} - -bool WinNativeWindow::ReleaseMouse() { - const auto result = ::ReleaseCapture(); - return result != 0; -} - -void WinNativeWindow::RequestRepaint() { - log::TagDebug(log_tag, u"A repaint is requested."); - if (!::InvalidateRect(hwnd_, nullptr, FALSE)) - throw Win32Error(::GetLastError(), "Failed to invalidate window."); - if (!::UpdateWindow(hwnd_)) - throw Win32Error(::GetLastError(), "Failed to update window."); -} - -std::unique_ptr WinNativeWindow::BeginPaint() { - return std::make_unique( - window_render_target_.get()); -} - -void WinNativeWindow::SetCursor(std::shared_ptr cursor) { - if (cursor == nullptr) { - throw std::runtime_error("Can't use a nullptr as cursor."); - } - - cursor_ = CheckPlatform(cursor, GetPlatformId()); - - if (!::SetClassLongPtrW(hwnd_, GCLP_HCURSOR, - reinterpret_cast(cursor_->GetHandle()))) { - log::TagWarn(log_tag, - u"Failed to set cursor because failed to set class long. Last " - u"error code: {}.", - ::GetLastError()); - return; - } - - if (!IsVisible()) return; - - auto lg = [](const std::u16string_view& reason) { - log::TagWarn( - log_tag, - u"Failed to set cursor because {} when window is visible. (We need to " - u"update cursor if it is inside the window.) Last error code: {}.", - reason, ::GetLastError()); - }; - - ::POINT point; - if (!::GetCursorPos(&point)) { - lg(u"failed to get cursor pos"); - return; - } - - ::RECT rect; - if (!::GetClientRect(hwnd_, &rect)) { - lg(u"failed to get window's client rect"); - return; - } - - ::POINT lefttop{rect.left, rect.top}; - ::POINT rightbottom{rect.right, rect.bottom}; - if (!::ClientToScreen(hwnd_, &lefttop)) { - lg(u"failed to call ClientToScreen on lefttop"); - return; - } - - if (!::ClientToScreen(hwnd_, &rightbottom)) { - lg(u"failed to call ClientToScreen on rightbottom"); - return; - } - - if (point.x >= lefttop.x && point.y >= lefttop.y && - point.x <= rightbottom.x && point.y <= rightbottom.y) { - ::SetCursor(cursor_->GetHandle()); - } -} - -IInputMethodContext* WinNativeWindow::GetInputMethodContext() { - return static_cast(input_method_context_.get()); -} - -bool WinNativeWindow::HandleNativeWindowMessage(HWND hwnd, UINT msg, - WPARAM w_param, LPARAM l_param, - LRESULT* result) { - WindowNativeMessageEventArgs args{ - WindowNativeMessage{hwnd, msg, w_param, l_param}}; - native_message_event_.Raise(args); - if (args.IsHandled()) { - *result = args.GetResult(); - return true; - } - - switch (msg) { - case WM_PAINT: - OnPaintInternal(); - *result = 0; - return true; - case WM_ERASEBKGND: - *result = 1; - return true; - case WM_SETFOCUS: - OnSetFocusInternal(); - *result = 0; - return true; - case WM_KILLFOCUS: - OnKillFocusInternal(); - *result = 0; - return true; - case WM_MOUSEMOVE: { - POINT point; - point.x = GET_X_LPARAM(l_param); - point.y = GET_Y_LPARAM(l_param); - OnMouseMoveInternal(point); - *result = 0; - return true; - } - case WM_LBUTTONDOWN: { - POINT point; - point.x = GET_X_LPARAM(l_param); - point.y = GET_Y_LPARAM(l_param); - OnMouseDownInternal(platform::native::mouse_buttons::left, point); - *result = 0; - return true; - } - case WM_LBUTTONUP: { - POINT point; - point.x = GET_X_LPARAM(l_param); - point.y = GET_Y_LPARAM(l_param); - OnMouseUpInternal(platform::native::mouse_buttons::left, point); - *result = 0; - return true; - } - case WM_RBUTTONDOWN: { - POINT point; - point.x = GET_X_LPARAM(l_param); - point.y = GET_Y_LPARAM(l_param); - OnMouseDownInternal(platform::native::mouse_buttons::right, point); - *result = 0; - return true; - } - case WM_RBUTTONUP: { - POINT point; - point.x = GET_X_LPARAM(l_param); - point.y = GET_Y_LPARAM(l_param); - OnMouseUpInternal(platform::native::mouse_buttons::right, point); - *result = 0; - return true; - } - case WM_MBUTTONDOWN: { - POINT point; - point.x = GET_X_LPARAM(l_param); - point.y = GET_Y_LPARAM(l_param); - OnMouseDownInternal(platform::native::mouse_buttons::middle, point); - *result = 0; - return true; - } - case WM_MBUTTONUP: { - POINT point; - point.x = GET_X_LPARAM(l_param); - point.y = GET_Y_LPARAM(l_param); - OnMouseUpInternal(platform::native::mouse_buttons::middle, point); - *result = 0; - return true; - } - case WM_MOUSEWHEEL: - POINT point; - point.x = GET_X_LPARAM(l_param); - point.y = GET_Y_LPARAM(l_param); - ScreenToClient(hwnd, &point); - OnMouseWheelInternal(GET_WHEEL_DELTA_WPARAM(w_param), point); - *result = 0; - return true; - case WM_KEYDOWN: - OnKeyDownInternal(static_cast(w_param)); - *result = 0; - return true; - case WM_KEYUP: - OnKeyUpInternal(static_cast(w_param)); - *result = 0; - return true; - case WM_SYSKEYDOWN: - if (l_param & (1 << 29)) { - OnKeyDownInternal(static_cast(w_param)); - *result = 0; - return true; - } - return false; - case WM_SYSKEYUP: - if (l_param & (1 << 29)) { - OnKeyUpInternal(static_cast(w_param)); - *result = 0; - return true; - } - return false; - case WM_SIZE: - OnResizeInternal(LOWORD(l_param), HIWORD(l_param)); - *result = 0; - return true; - case WM_ACTIVATE: - if (w_param == WA_ACTIVE || w_param == WA_CLICKACTIVE) - OnActivatedInternal(); - else if (w_param == WA_INACTIVE) - OnDeactivatedInternal(); - *result = 0; - return true; - case WM_DESTROY: - OnDestroyInternal(); - *result = 0; - return true; - case WM_IME_SETCONTEXT: - l_param &= ~ISC_SHOWUICOMPOSITIONWINDOW; - *result = ::DefWindowProcW(hwnd, msg, w_param, l_param); - return true; - // We must block these message from DefWindowProc or it will create - // an ugly composition window. - case WM_IME_STARTCOMPOSITION: - case WM_IME_COMPOSITION: - *result = 0; - return true; - case WM_DPICHANGED: { - dpi_ = static_cast(LOWORD(w_param)); - const RECT* suggest_rect = reinterpret_cast(l_param); - window_render_target_->SetDpi(dpi_, dpi_); - SetWindowPos(hwnd_, NULL, suggest_rect->left, suggest_rect->top, - suggest_rect->right - suggest_rect->left, - suggest_rect->bottom - suggest_rect->top, - SWP_NOZORDER | SWP_NOACTIVATE); - } - default: - return false; - } -} - -RECT WinNativeWindow::GetClientRectPixel() { - RECT rect; - if (!GetClientRect(hwnd_, &rect)) - throw Win32Error(::GetLastError(), "Failed to invoke GetClientRect."); - return rect; -} - -void WinNativeWindow::OnDestroyInternal() { - application_->GetWindowManager()->UnregisterWindow(hwnd_); - hwnd_ = nullptr; - destroy_event_.Raise(nullptr); - if (!sync_flag_) { - sync_flag_ = true; - delete this; - } -} - -void WinNativeWindow::OnPaintInternal() { - paint_event_.Raise(nullptr); - ValidateRect(hwnd_, nullptr); - log::TagDebug(log_tag, u"A repaint is finished."); -} - -void WinNativeWindow::OnResizeInternal(const int new_width, - const int new_height) { - if (!(new_width == 0 && new_height == 0)) { - window_render_target_->ResizeBuffer(new_width, new_height); - resize_event_.Raise(Size{PixelToDip(new_width), PixelToDip(new_height)}); - } -} - -void WinNativeWindow::OnSetFocusInternal() { - has_focus_ = true; - focus_event_.Raise(FocusChangeType::Gain); -} - -void WinNativeWindow::OnKillFocusInternal() { - has_focus_ = false; - focus_event_.Raise(FocusChangeType::Lost); -} - -void WinNativeWindow::OnMouseMoveInternal(const POINT point) { - // when mouse was previous outside the window - if (!is_mouse_in_) { - // invoke TrackMouseEvent to have WM_MOUSELEAVE sent. - TRACKMOUSEEVENT tme; - tme.cbSize = sizeof tme; - tme.dwFlags = TME_LEAVE; - tme.hwndTrack = hwnd_; - - TrackMouseEvent(&tme); - - is_mouse_in_ = true; - mouse_enter_leave_event_.Raise(MouseEnterLeaveType::Enter); - } - - mouse_move_event_.Raise(PixelToDip(point)); -} - -void WinNativeWindow::OnMouseLeaveInternal() { - is_mouse_in_ = false; - mouse_enter_leave_event_.Raise(MouseEnterLeaveType::Leave); -} - -void WinNativeWindow::OnMouseDownInternal(platform::native::MouseButton button, - POINT point) { - const auto dip_point = PixelToDip(point); - mouse_down_event_.Raise({button, dip_point, RetrieveKeyMofifier()}); -} - -void WinNativeWindow::OnMouseUpInternal(platform::native::MouseButton button, - POINT point) { - const auto dip_point = PixelToDip(point); - mouse_up_event_.Raise({button, dip_point, RetrieveKeyMofifier()}); -} - -void WinNativeWindow::OnMouseWheelInternal(short delta, POINT point) { - CRU_UNUSED(delta) - CRU_UNUSED(point) -} - -void WinNativeWindow::OnKeyDownInternal(int virtual_code) { - key_down_event_.Raise( - {VirtualKeyToKeyCode(virtual_code), RetrieveKeyMofifier()}); -} - -void WinNativeWindow::OnKeyUpInternal(int virtual_code) { - key_up_event_.Raise( - {VirtualKeyToKeyCode(virtual_code), RetrieveKeyMofifier()}); -} - -void WinNativeWindow::OnActivatedInternal() {} - -void WinNativeWindow::OnDeactivatedInternal() {} -} // namespace cru::platform::native::win diff --git a/src/win/native/WindowClass.cpp b/src/win/native/WindowClass.cpp deleted file mode 100644 index 2e74606e..00000000 --- a/src/win/native/WindowClass.cpp +++ /dev/null @@ -1,28 +0,0 @@ -#include "cru/win/native/WindowClass.hpp" - -#include "cru/win/native/Exception.hpp" - -namespace cru::platform::native::win { -WindowClass::WindowClass(std::wstring name, WNDPROC window_proc, - HINSTANCE h_instance) - : name_(std::move(name)) { - WNDCLASSEXW window_class; - window_class.cbSize = sizeof(WNDCLASSEXW); - - window_class.style = CS_HREDRAW | CS_VREDRAW; - window_class.lpfnWndProc = window_proc; - window_class.cbClsExtra = 0; - window_class.cbWndExtra = 0; - window_class.hInstance = h_instance; - window_class.hIcon = LoadIcon(NULL, IDI_APPLICATION); - window_class.hCursor = LoadCursor(NULL, IDC_ARROW); - window_class.hbrBackground = GetSysColorBrush(COLOR_BTNFACE); - window_class.lpszMenuName = NULL; - window_class.lpszClassName = name_.c_str(); - window_class.hIconSm = NULL; - - atom_ = ::RegisterClassExW(&window_class); - if (atom_ == 0) - throw Win32Error(::GetLastError(), "Failed to create window class."); -} -} // namespace cru::platform::native::win diff --git a/src/win/native/WindowManager.cpp b/src/win/native/WindowManager.cpp deleted file mode 100644 index 56cc8981..00000000 --- a/src/win/native/WindowManager.cpp +++ /dev/null @@ -1,56 +0,0 @@ -#include "WindowManager.hpp" - -#include "cru/win/native/UiApplication.hpp" -#include "cru/win/native/Window.hpp" -#include "cru/win/native/WindowClass.hpp" - -namespace cru::platform::native::win { -LRESULT __stdcall GeneralWndProc(HWND hWnd, UINT Msg, WPARAM wParam, - LPARAM lParam) { - auto window = - WinUiApplication::GetInstance()->GetWindowManager()->FromHandle(hWnd); - - LRESULT result; - if (window != nullptr && - window->HandleNativeWindowMessage(hWnd, Msg, wParam, lParam, &result)) - return result; - - return DefWindowProc(hWnd, Msg, wParam, lParam); -} - -WindowManager::WindowManager(WinUiApplication* application) { - application_ = application; - general_window_class_ = std::make_unique( - L"CruUIWindowClass", GeneralWndProc, application->GetInstanceHandle()); -} - -WindowManager::~WindowManager() { - for (const auto& [key, window] : window_map_) delete window; -} - -void WindowManager::RegisterWindow(HWND hwnd, WinNativeWindow* window) { - Expects(window_map_.count(hwnd) == 0); // The hwnd is already in the map. - window_map_.emplace(hwnd, window); -} - -void WindowManager::UnregisterWindow(HWND hwnd) { - const auto find_result = window_map_.find(hwnd); - Expects(find_result != window_map_.end()); // The hwnd is not in the map. - window_map_.erase(find_result); - if (window_map_.empty()) application_->RequestQuit(0); -} - -WinNativeWindow* WindowManager::FromHandle(HWND hwnd) { - const auto find_result = window_map_.find(hwnd); - if (find_result == window_map_.end()) - return nullptr; - else - return find_result->second; -} - -std::vector WindowManager::GetAllWindows() const { - std::vector windows; - for (const auto& [key, value] : window_map_) windows.push_back(value); - return windows; -} -} // namespace cru::platform::native::win diff --git a/src/win/native/WindowManager.hpp b/src/win/native/WindowManager.hpp deleted file mode 100644 index 3f6387f7..00000000 --- a/src/win/native/WindowManager.hpp +++ /dev/null @@ -1,51 +0,0 @@ -#pragma once -#include "cru/win/WinPreConfig.hpp" - -#include "cru/common/Base.hpp" - -#include -#include -#include - -namespace cru::platform::native::win { -class WinUiApplication; -class WinNativeWindow; -class WindowClass; - -class WindowManager : public Object { - public: - WindowManager(WinUiApplication* application); - - CRU_DELETE_COPY(WindowManager) - CRU_DELETE_MOVE(WindowManager) - - ~WindowManager() override; - - // Get the general window class for creating ordinary window. - WindowClass* GetGeneralWindowClass() const { - return general_window_class_.get(); - } - - // Register a window newly created. - // This function adds the hwnd to hwnd-window map. - // It should be called immediately after a window was created. - void RegisterWindow(HWND hwnd, WinNativeWindow* window); - - // Unregister a window that is going to be destroyed. - // This function removes the hwnd from the hwnd-window map. - // It should be called immediately before a window is going to be destroyed, - void UnregisterWindow(HWND hwnd); - - // Return a pointer to the Window object related to the HWND or nullptr if the - // hwnd is not in the map. - WinNativeWindow* FromHandle(HWND hwnd); - - std::vector GetAllWindows() const; - - private: - WinUiApplication* application_; - - std::unique_ptr general_window_class_; - std::map window_map_; -}; -} // namespace cru::platform::native::win -- cgit v1.2.3 From a176c40ba0f913f98e966f11bad557833ae6dc57 Mon Sep 17 00:00:00 2001 From: crupest Date: Fri, 30 Oct 2020 11:25:57 +0800 Subject: ... --- demos/main/main.cpp | 2 +- include/cru/ui/Base.hpp | 3 + include/cru/ui/Control.hpp | 10 +- include/cru/ui/Window.hpp | 2 +- include/cru/ui/WindowHost.hpp | 142 ------------ include/cru/ui/host/WindowHost.hpp | 142 ++++++++++++ include/cru/ui/render/RenderObject.hpp | 12 +- src/ui/CMakeLists.txt | 6 +- src/ui/Control.cpp | 9 +- src/ui/RoutedEventDispatch.hpp | 110 --------- src/ui/Window.cpp | 4 +- src/ui/WindowHost.cpp | 400 --------------------------------- src/ui/controls/TextControlService.hpp | 4 +- src/ui/host/RoutedEventDispatch.hpp | 110 +++++++++ src/ui/host/WindowHost.cpp | 400 +++++++++++++++++++++++++++++++++ src/ui/render/RenderObject.cpp | 4 +- 16 files changed, 681 insertions(+), 679 deletions(-) delete mode 100644 include/cru/ui/WindowHost.hpp create mode 100644 include/cru/ui/host/WindowHost.hpp delete mode 100644 src/ui/RoutedEventDispatch.hpp delete mode 100644 src/ui/WindowHost.cpp create mode 100644 src/ui/host/RoutedEventDispatch.hpp create mode 100644 src/ui/host/WindowHost.cpp (limited to 'demos/main/main.cpp') diff --git a/demos/main/main.cpp b/demos/main/main.cpp index 6bd7fb4e..5546f3dd 100644 --- a/demos/main/main.cpp +++ b/demos/main/main.cpp @@ -3,7 +3,7 @@ #include "cru/platform/gui/Window.hpp" #include "cru/ui/Base.hpp" #include "cru/ui/Window.hpp" -#include "cru/ui/WindowHost.hpp" +#include "cru/ui/host/WindowHost.hpp" #include "cru/ui/controls/Button.hpp" #include "cru/ui/controls/FlexLayout.hpp" #include "cru/ui/controls/TextBlock.hpp" diff --git a/include/cru/ui/Base.hpp b/include/cru/ui/Base.hpp index 36d0eb78..39fbb035 100644 --- a/include/cru/ui/Base.hpp +++ b/include/cru/ui/Base.hpp @@ -29,7 +29,10 @@ namespace colors = cru::platform::colors; class Window; class Control; class ClickDetector; + +namespace host { class WindowHost; +} namespace render { class RenderObject; diff --git a/include/cru/ui/Control.hpp b/include/cru/ui/Control.hpp index 5f381965..fe50624a 100644 --- a/include/cru/ui/Control.hpp +++ b/include/cru/ui/Control.hpp @@ -9,7 +9,7 @@ namespace cru::ui { class Control : public Object { - friend WindowHost; + friend host::WindowHost; protected: Control(); @@ -26,7 +26,7 @@ class Control : public Object { //*************** region: tree *************** public: - WindowHost* GetWindowHost() const; + host::WindowHost* GetWindowHost() const; Control* GetParent() const { return parent_; } @@ -131,8 +131,8 @@ class Control : public Object { virtual void OnAddChild(Control* child, Index position); virtual void OnRemoveChild(Control* child, Index position); virtual void OnParentChanged(Control* old_parent, Control* new_parent); - virtual void OnAttachToHost(WindowHost* host); - virtual void OnDetachFromHost(WindowHost* host); + virtual void OnAttachToHost(host::WindowHost* host); + virtual void OnDetachFromHost(host::WindowHost* host); protected: virtual void OnMouseHoverChange(bool newHover) { CRU_UNUSED(newHover) } @@ -141,7 +141,7 @@ class Control : public Object { Control* parent_ = nullptr; std::vector children_; - WindowHost* window_host_ = nullptr; + host::WindowHost* window_host_ = nullptr; private: bool is_mouse_over_ = false; diff --git a/include/cru/ui/Window.hpp b/include/cru/ui/Window.hpp index 0739e3dc..70423a14 100644 --- a/include/cru/ui/Window.hpp +++ b/include/cru/ui/Window.hpp @@ -29,7 +29,7 @@ class Window final : public LayoutControl { void OnRemoveChild(Control* child, Index position) override; private: - std::unique_ptr window_host_; + std::unique_ptr window_host_; std::unique_ptr render_object_; }; diff --git a/include/cru/ui/WindowHost.hpp b/include/cru/ui/WindowHost.hpp deleted file mode 100644 index 7f7d62f0..00000000 --- a/include/cru/ui/WindowHost.hpp +++ /dev/null @@ -1,142 +0,0 @@ -#pragma once -#include "Base.hpp" - -#include "cru/common/Event.hpp" -#include "cru/platform/gui/UiApplication.hpp" -#include "cru/platform/gui/Window.hpp" -#include "render/Base.hpp" - -#include - -namespace cru::ui { -struct AfterLayoutEventArgs {}; - -// The bridge between control tree and native window. -class WindowHost : public Object { - CRU_DEFINE_CLASS_LOG_TAG(u"cru::ui::WindowHost") - - public: - WindowHost(Control* root_control); - - CRU_DELETE_COPY(WindowHost) - CRU_DELETE_MOVE(WindowHost) - - ~WindowHost() override; - - public: - platform::gui::INativeWindow* GetNativeWindow() { return native_window_; } - - // Mark the layout as invalid, and arrange a re-layout later. - // This method could be called more than one times in a message cycle. But - // layout only takes place once. - void InvalidateLayout(); - - // Mark the paint as invalid, and arrange a re-paint later. - // This method could be called more than one times in a message cycle. But - // paint only takes place once. - void InvalidatePaint(); - - IEvent* AfterLayoutEvent() { - return &after_layout_event_; - } - - void Relayout(); - void Relayout(const Size& available_size); - - // Is layout is invalid, wait for relayout and then run the action. Otherwist - // run it right now. - void RunAfterLayoutStable(std::function action); - - // If true, preferred size of root render object is set to window size when - // measure. Default is true. - bool IsLayoutPreferToFillWindow() const; - void SetLayoutPreferToFillWindow(bool value); - - // Get current control that mouse hovers on. This ignores the mouse-capture - // control. Even when mouse is captured by another control, this function - // return the control under cursor. You can use `GetMouseCaptureControl` to - // get more info. - Control* GetMouseHoverControl() const { return mouse_hover_control_; } - - //*************** region: focus *************** - - Control* GetFocusControl(); - - void SetFocusControl(Control* control); - - //*************** region: focus *************** - - // Pass nullptr to release capture. If mouse is already capture by a control, - // this capture will fail and return false. If control is identical to the - // capturing control, capture is not changed and this function will return - // true. - // - // When capturing control changes, - // appropriate event will be sent. If mouse is not on the capturing control - // and capture is released, mouse enter event will be sent to the mouse-hover - // control. If mouse is not on the capturing control and capture is set, mouse - // leave event will be sent to the mouse-hover control. - bool CaptureMouseFor(Control* control); - - // Return null if not captured. - Control* GetMouseCaptureControl(); - - Control* HitTest(const Point& point); - - void UpdateCursor(); - - private: - //*************** region: native messages *************** - void OnNativeDestroy(platform::gui::INativeWindow* window, std::nullptr_t); - void OnNativePaint(platform::gui::INativeWindow* window, std::nullptr_t); - void OnNativeResize(platform::gui::INativeWindow* window, - const Size& size); - - void OnNativeFocus(platform::gui::INativeWindow* window, - cru::platform::gui::FocusChangeType focus); - - void OnNativeMouseEnterLeave( - platform::gui::INativeWindow* window, - cru::platform::gui::MouseEnterLeaveType enter); - void OnNativeMouseMove(platform::gui::INativeWindow* window, - const Point& point); - void OnNativeMouseDown( - platform::gui::INativeWindow* window, - const platform::gui::NativeMouseButtonEventArgs& args); - void OnNativeMouseUp( - platform::gui::INativeWindow* window, - const platform::gui::NativeMouseButtonEventArgs& args); - - void OnNativeKeyDown(platform::gui::INativeWindow* window, - const platform::gui::NativeKeyEventArgs& args); - void OnNativeKeyUp(platform::gui::INativeWindow* window, - const platform::gui::NativeKeyEventArgs& args); - - //*************** region: event dispatcher helper *************** - - void DispatchMouseHoverControlChangeEvent(Control* old_control, - Control* new_control, - const Point& point, bool no_leave, - bool no_enter); - - private: - Control* root_control_ = nullptr; - render::RenderObject* root_render_object_ = nullptr; - - platform::gui::INativeWindow* native_window_ = nullptr; - - bool need_layout_ = false; - Event after_layout_event_; - std::vector > after_layout_stable_action_; - - std::vector event_revoker_guards_; - - Control* mouse_hover_control_ = nullptr; - - Control* focus_control_; - - Control* mouse_captured_control_ = nullptr; - - bool layout_prefer_to_fill_window_ = true; -}; -} // namespace cru::ui diff --git a/include/cru/ui/host/WindowHost.hpp b/include/cru/ui/host/WindowHost.hpp new file mode 100644 index 00000000..77ed937f --- /dev/null +++ b/include/cru/ui/host/WindowHost.hpp @@ -0,0 +1,142 @@ +#pragma once +#include "../Base.hpp" + +#include "cru/common/Event.hpp" +#include "cru/platform/gui/UiApplication.hpp" +#include "cru/platform/gui/Window.hpp" +#include "../render/Base.hpp" + +#include + +namespace cru::ui::host { +struct AfterLayoutEventArgs {}; + +// The bridge between control tree and native window. +class WindowHost : public Object { + CRU_DEFINE_CLASS_LOG_TAG(u"cru::ui::host::WindowHost") + + public: + WindowHost(Control* root_control); + + CRU_DELETE_COPY(WindowHost) + CRU_DELETE_MOVE(WindowHost) + + ~WindowHost() override; + + public: + platform::gui::INativeWindow* GetNativeWindow() { return native_window_; } + + // Mark the layout as invalid, and arrange a re-layout later. + // This method could be called more than one times in a message cycle. But + // layout only takes place once. + void InvalidateLayout(); + + // Mark the paint as invalid, and arrange a re-paint later. + // This method could be called more than one times in a message cycle. But + // paint only takes place once. + void InvalidatePaint(); + + IEvent* AfterLayoutEvent() { + return &after_layout_event_; + } + + void Relayout(); + void Relayout(const Size& available_size); + + // Is layout is invalid, wait for relayout and then run the action. Otherwist + // run it right now. + void RunAfterLayoutStable(std::function action); + + // If true, preferred size of root render object is set to window size when + // measure. Default is true. + bool IsLayoutPreferToFillWindow() const; + void SetLayoutPreferToFillWindow(bool value); + + // Get current control that mouse hovers on. This ignores the mouse-capture + // control. Even when mouse is captured by another control, this function + // return the control under cursor. You can use `GetMouseCaptureControl` to + // get more info. + Control* GetMouseHoverControl() const { return mouse_hover_control_; } + + //*************** region: focus *************** + + Control* GetFocusControl(); + + void SetFocusControl(Control* control); + + //*************** region: focus *************** + + // Pass nullptr to release capture. If mouse is already capture by a control, + // this capture will fail and return false. If control is identical to the + // capturing control, capture is not changed and this function will return + // true. + // + // When capturing control changes, + // appropriate event will be sent. If mouse is not on the capturing control + // and capture is released, mouse enter event will be sent to the mouse-hover + // control. If mouse is not on the capturing control and capture is set, mouse + // leave event will be sent to the mouse-hover control. + bool CaptureMouseFor(Control* control); + + // Return null if not captured. + Control* GetMouseCaptureControl(); + + Control* HitTest(const Point& point); + + void UpdateCursor(); + + private: + //*************** region: native messages *************** + void OnNativeDestroy(platform::gui::INativeWindow* window, std::nullptr_t); + void OnNativePaint(platform::gui::INativeWindow* window, std::nullptr_t); + void OnNativeResize(platform::gui::INativeWindow* window, + const Size& size); + + void OnNativeFocus(platform::gui::INativeWindow* window, + cru::platform::gui::FocusChangeType focus); + + void OnNativeMouseEnterLeave( + platform::gui::INativeWindow* window, + cru::platform::gui::MouseEnterLeaveType enter); + void OnNativeMouseMove(platform::gui::INativeWindow* window, + const Point& point); + void OnNativeMouseDown( + platform::gui::INativeWindow* window, + const platform::gui::NativeMouseButtonEventArgs& args); + void OnNativeMouseUp( + platform::gui::INativeWindow* window, + const platform::gui::NativeMouseButtonEventArgs& args); + + void OnNativeKeyDown(platform::gui::INativeWindow* window, + const platform::gui::NativeKeyEventArgs& args); + void OnNativeKeyUp(platform::gui::INativeWindow* window, + const platform::gui::NativeKeyEventArgs& args); + + //*************** region: event dispatcher helper *************** + + void DispatchMouseHoverControlChangeEvent(Control* old_control, + Control* new_control, + const Point& point, bool no_leave, + bool no_enter); + + private: + Control* root_control_ = nullptr; + render::RenderObject* root_render_object_ = nullptr; + + platform::gui::INativeWindow* native_window_ = nullptr; + + bool need_layout_ = false; + Event after_layout_event_; + std::vector > after_layout_stable_action_; + + std::vector event_revoker_guards_; + + Control* mouse_hover_control_ = nullptr; + + Control* focus_control_; + + Control* mouse_captured_control_ = nullptr; + + bool layout_prefer_to_fill_window_ = true; +}; +} // namespace cru::ui diff --git a/include/cru/ui/render/RenderObject.hpp b/include/cru/ui/render/RenderObject.hpp index 436cf6b2..635a541e 100644 --- a/include/cru/ui/render/RenderObject.hpp +++ b/include/cru/ui/render/RenderObject.hpp @@ -39,7 +39,7 @@ namespace cru::ui::render { // Size OnMeasureContent(const MeasureRequirement& requirement) override; // void OnLayoutContent(const Rect& content_rect) override; class RenderObject : public Object { - friend WindowHost; + friend host::WindowHost; CRU_DEFINE_CLASS_LOG_TAG(u"cru::ui::render::RenderObject") @@ -65,7 +65,7 @@ class RenderObject : public Object { Control* GetAttachedControl() const { return control_; } void SetAttachedControl(Control* new_control) { control_ = new_control; } - WindowHost* GetWindowHost() const { return window_host_; } + host::WindowHost* GetWindowHost() const { return window_host_; } RenderObject* GetParent() const { return parent_; } @@ -135,7 +135,7 @@ class RenderObject : public Object { // Add offset before pass point to children. virtual RenderObject* HitTest(const Point& point) = 0; - IEvent* AttachToHostEvent() { return &attach_to_host_event_; } + IEvent* AttachToHostEvent() { return &attach_to_host_event_; } IEvent* DetachFromHostEvent() { return &detach_from_host_event_; } @@ -205,11 +205,11 @@ class RenderObject : public Object { private: void SetParent(RenderObject* new_parent); - void SetWindowHostRecursive(WindowHost* host); + void SetWindowHostRecursive(host::WindowHost* host); private: Control* control_ = nullptr; - WindowHost* window_host_ = nullptr; + host::WindowHost* window_host_ = nullptr; RenderObject* parent_ = nullptr; std::vector children_{}; @@ -225,7 +225,7 @@ class RenderObject : public Object { Thickness margin_{}; Thickness padding_{}; - Event attach_to_host_event_; + Event attach_to_host_event_; Event detach_from_host_event_; }; } // namespace cru::ui::render diff --git a/src/ui/CMakeLists.txt b/src/ui/CMakeLists.txt index 45f64c88..d7b924cb 100644 --- a/src/ui/CMakeLists.txt +++ b/src/ui/CMakeLists.txt @@ -2,7 +2,7 @@ set(CRU_UI_INCLUDE_DIR ${CRU_INCLUDE_DIR}/cru/ui) add_library(cru_ui STATIC Helper.hpp - RoutedEventDispatch.hpp + host/RoutedEventDispatch.hpp ClickDetector.cpp ContentControl.cpp @@ -14,7 +14,6 @@ add_library(cru_ui STATIC UiEvent.cpp UiManager.cpp Window.cpp - WindowHost.cpp controls/Button.cpp controls/Container.cpp controls/FlexLayout.cpp @@ -22,6 +21,7 @@ add_library(cru_ui STATIC controls/TextBlock.cpp controls/TextBox.cpp controls/TextControlService.hpp + host/WindowHost.cpp render/BorderRenderObject.cpp render/CanvasRenderObject.cpp render/FlexLayoutRenderObject.cpp @@ -43,7 +43,6 @@ target_sources(cru_ui PUBLIC ${CRU_UI_INCLUDE_DIR}/UiEvent.hpp ${CRU_UI_INCLUDE_DIR}/UiManager.hpp ${CRU_UI_INCLUDE_DIR}/Window.hpp - ${CRU_UI_INCLUDE_DIR}/WindowHost.hpp ${CRU_UI_INCLUDE_DIR}/controls/Base.hpp ${CRU_UI_INCLUDE_DIR}/controls/Button.hpp ${CRU_UI_INCLUDE_DIR}/controls/Container.hpp @@ -51,6 +50,7 @@ target_sources(cru_ui PUBLIC ${CRU_UI_INCLUDE_DIR}/controls/StackLayout.hpp ${CRU_UI_INCLUDE_DIR}/controls/TextBox.hpp ${CRU_UI_INCLUDE_DIR}/controls/TextBlock.hpp + ${CRU_UI_INCLUDE_DIR}/host/WindowHost.hpp ${CRU_UI_INCLUDE_DIR}/render/Base.hpp ${CRU_UI_INCLUDE_DIR}/render/BorderRenderObject.hpp ${CRU_UI_INCLUDE_DIR}/render/CanvasRenderObject.hpp diff --git a/src/ui/Control.cpp b/src/ui/Control.cpp index cae48c66..23a3cef2 100644 --- a/src/ui/Control.cpp +++ b/src/ui/Control.cpp @@ -1,11 +1,10 @@ #include "cru/ui/Control.hpp" -#include "RoutedEventDispatch.hpp" #include "cru/common/Base.hpp" #include "cru/platform/gui/Cursor.hpp" #include "cru/platform/gui/UiApplication.hpp" #include "cru/ui/Base.hpp" -#include "cru/ui/WindowHost.hpp" +#include "cru/ui/host/WindowHost.hpp" #include "cru/ui/render/RenderObject.hpp" #include @@ -31,7 +30,7 @@ Control::~Control() { for (const auto child : children_) delete child; } -WindowHost* Control::GetWindowHost() const { return window_host_; } +host::WindowHost* Control::GetWindowHost() const { return window_host_; } void Control::TraverseDescendants( const std::function& predicate) { @@ -152,7 +151,7 @@ void Control::OnParentChanged(Control* old_parent, Control* new_parent) { CRU_UNUSED(new_parent) } -void Control::OnAttachToHost(WindowHost* host) { CRU_UNUSED(host) } +void Control::OnAttachToHost(host::WindowHost* host) { CRU_UNUSED(host) } -void Control::OnDetachFromHost(WindowHost* host) { CRU_UNUSED(host) } +void Control::OnDetachFromHost(host::WindowHost* host) { CRU_UNUSED(host) } } // namespace cru::ui diff --git a/src/ui/RoutedEventDispatch.hpp b/src/ui/RoutedEventDispatch.hpp deleted file mode 100644 index de94a598..00000000 --- a/src/ui/RoutedEventDispatch.hpp +++ /dev/null @@ -1,110 +0,0 @@ -#pragma once -#include "cru/ui/Control.hpp" - -#include "cru/common/Logger.hpp" -#include "cru/ui/DebugFlags.hpp" - -#include - -namespace cru::ui { -// Dispatch the event. -// -// This will raise routed event of the control and its parent and parent's -// parent ... (until "last_receiver" if it's not nullptr) with appropriate args. -// -// First tunnel from top to bottom possibly stopped by "handled" flag in -// EventArgs. Second bubble from bottom to top possibly stopped by "handled" -// flag in EventArgs. Last direct to each control. -// -// Args is of type "EventArgs". The first init argument is "sender", which is -// automatically bound to each receiving control. The second init argument is -// "original_sender", which is unchanged. And "args" will be perfectly forwarded -// as the rest arguments. -template -void DispatchEvent(const std::u16string_view& event_name, - Control* const original_sender, - event::RoutedEvent* (Control::*event_ptr)(), - Control* const last_receiver, Args&&... args) { - CRU_UNUSED(event_name) - - if (original_sender == last_receiver) { - if constexpr (debug_flags::routed_event) - log::Debug( - "Routed event {} no need to dispatch (original_sender == " - "last_receiver). Original sender is {}.", - event_name, original_sender->GetControlType()); - return; - } - - std::vector receive_list; - - auto parent = original_sender; - while (parent != last_receiver) { - receive_list.push_back(parent); - parent = parent->GetParent(); - } - - if constexpr (debug_flags::routed_event) { - std::u16string log = u"Dispatch routed event "; - log += event_name; - log += u". Path (parent first): "; - auto i = receive_list.crbegin(); - const auto end = --receive_list.crend(); - for (; i != end; ++i) { - log += (*i)->GetControlType(); - log += u" -> "; - } - log += (*i)->GetControlType(); - log::Debug(log); - } - - auto handled = false; - - int count = 0; - - // tunnel - for (auto i = receive_list.crbegin(); i != receive_list.crend(); ++i) { - count++; - EventArgs event_args(*i, original_sender, std::forward(args)...); - static_cast*>(((*i)->*event_ptr)()->Tunnel()) - ->Raise(event_args); - if (event_args.IsHandled()) { - handled = true; - if constexpr (debug_flags::routed_event) - log::Debug( - u"Routed event is short-circuit in TUNNEL at {}-st control (count " - u"from parent).", - count); - break; - } - } - - // bubble - if (!handled) { - for (auto i : receive_list) { - count--; - EventArgs event_args(i, original_sender, std::forward(args)...); - static_cast*>((i->*event_ptr)()->Bubble()) - ->Raise(event_args); - if (event_args.IsHandled()) { - if constexpr (debug_flags::routed_event) - log::Debug( - u"Routed event is short-circuit in BUBBLE at {}-st control " - u"(count from parent).", - count); - break; - } - } - } - - // direct - for (auto i : receive_list) { - EventArgs event_args(i, original_sender, std::forward(args)...); - static_cast*>((i->*event_ptr)()->Direct()) - ->Raise(event_args); - } - - if constexpr (debug_flags::routed_event) - log::Debug(u"Routed event dispatch finished."); -} -} // namespace cru::ui diff --git a/src/ui/Window.cpp b/src/ui/Window.cpp index 051e67ef..c49140a4 100644 --- a/src/ui/Window.cpp +++ b/src/ui/Window.cpp @@ -1,7 +1,7 @@ #include "cru/ui/Window.hpp" #include "cru/common/Base.hpp" -#include "cru/ui/WindowHost.hpp" +#include "cru/ui/host/WindowHost.hpp" #include "cru/ui/render/Base.hpp" #include "cru/ui/render/StackLayoutRenderObject.hpp" @@ -10,7 +10,7 @@ Window* Window::CreateOverlapped() { return new Window(); } Window::Window() : render_object_(new render::StackLayoutRenderObject()) { render_object_->SetAttachedControl(this); - window_host_ = std::make_unique(this); + window_host_ = std::make_unique(this); } Window::~Window() {} diff --git a/src/ui/WindowHost.cpp b/src/ui/WindowHost.cpp deleted file mode 100644 index b0908e4f..00000000 --- a/src/ui/WindowHost.cpp +++ /dev/null @@ -1,400 +0,0 @@ -#include "cru/ui/WindowHost.hpp" - -#include "RoutedEventDispatch.hpp" -#include "cru/common/Logger.hpp" -#include "cru/platform/graphics/Painter.hpp" -#include "cru/platform/gui/InputMethod.hpp" -#include "cru/platform/gui/UiApplication.hpp" -#include "cru/platform/gui/Window.hpp" -#include "cru/ui/DebugFlags.hpp" -#include "cru/ui/Window.hpp" -#include "cru/ui/render/MeasureRequirement.hpp" -#include "cru/ui/render/RenderObject.hpp" - -#include - -namespace cru::ui { -using platform::gui::INativeWindow; -using platform::gui::IUiApplication; - -namespace event_names { -#ifdef CRU_DEBUG -// clang-format off -#define CRU_DEFINE_EVENT_NAME(name) constexpr const char16_t* name = CRU_MAKE_UNICODE_LITERAL(name); -// clang-format on -#else -#define CRU_DEFINE_EVENT_NAME(name) constexpr const char16_t* name = u""; -#endif - -CRU_DEFINE_EVENT_NAME(LoseFocus) -CRU_DEFINE_EVENT_NAME(GainFocus) -CRU_DEFINE_EVENT_NAME(MouseEnter) -CRU_DEFINE_EVENT_NAME(MouseLeave) -CRU_DEFINE_EVENT_NAME(MouseMove) -CRU_DEFINE_EVENT_NAME(MouseDown) -CRU_DEFINE_EVENT_NAME(MouseUp) -CRU_DEFINE_EVENT_NAME(KeyDown) -CRU_DEFINE_EVENT_NAME(KeyUp) - -#undef CRU_DEFINE_EVENT_NAME -} // namespace event_names - -namespace { -bool IsAncestor(Control* control, Control* ancestor) { - while (control != nullptr) { - if (control == ancestor) return true; - control = control->GetParent(); - } - return false; -} - -// Ancestor at last. -std::vector GetAncestorList(Control* control) { - std::vector l; - while (control != nullptr) { - l.push_back(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.back() != right_list.back()) return nullptr; - - // find the last same control or the last control (one is ancestor of the - // other) - auto left_iter = left_list.crbegin(); - auto right_iter = right_list.crbegin(); - - while (true) { - if (left_iter == left_list.crend()) { - return left_list.front(); - } - if (right_iter == right_list.crend()) { - return right_list.front(); - } - if (*left_iter != *right_iter) { - return *(--left_iter); - } - ++left_iter; - ++right_iter; - } -} -} // namespace - -namespace { -template -inline void BindNativeEvent( - WindowHost* host, INativeWindow* native_window, IEvent* event, - void (WindowHost::*handler)(INativeWindow*, typename IEvent::EventArgs), - std::vector& guard_pool) { - guard_pool.push_back(EventRevokerGuard(event->AddHandler( - std::bind(handler, host, native_window, std::placeholders::_1)))); -} -} // namespace - -WindowHost::WindowHost(Control* root_control) - : root_control_(root_control), focus_control_(root_control) { - const auto ui_application = IUiApplication::GetInstance(); - auto native_window = ui_application->CreateWindow(nullptr); - native_window_ = native_window; - - root_control_->TraverseDescendants([this](Control* control) { - control->window_host_ = this; - control->OnAttachToHost(this); - }); - - root_render_object_ = root_control->GetRenderObject(); - root_render_object_->SetWindowHostRecursive(this); - - BindNativeEvent(this, native_window, native_window->DestroyEvent(), - &WindowHost::OnNativeDestroy, event_revoker_guards_); - BindNativeEvent(this, native_window, native_window->PaintEvent(), - &WindowHost::OnNativePaint, event_revoker_guards_); - BindNativeEvent(this, native_window, native_window->ResizeEvent(), - &WindowHost::OnNativeResize, event_revoker_guards_); - BindNativeEvent(this, native_window, native_window->FocusEvent(), - &WindowHost::OnNativeFocus, event_revoker_guards_); - BindNativeEvent(this, native_window, native_window->MouseEnterLeaveEvent(), - &WindowHost::OnNativeMouseEnterLeave, event_revoker_guards_); - BindNativeEvent(this, native_window, native_window->MouseMoveEvent(), - &WindowHost::OnNativeMouseMove, event_revoker_guards_); - BindNativeEvent(this, native_window, native_window->MouseDownEvent(), - &WindowHost::OnNativeMouseDown, event_revoker_guards_); - BindNativeEvent(this, native_window, native_window->MouseUpEvent(), - &WindowHost::OnNativeMouseUp, event_revoker_guards_); - BindNativeEvent(this, native_window, native_window->KeyDownEvent(), - &WindowHost::OnNativeKeyDown, event_revoker_guards_); - BindNativeEvent(this, native_window, native_window->KeyUpEvent(), - &WindowHost::OnNativeKeyUp, event_revoker_guards_); -} - -WindowHost::~WindowHost() { - if (native_window_) { - native_window_->Close(); - } -} - -void WindowHost::InvalidatePaint() { - if (native_window_) native_window_->RequestRepaint(); -} - -void WindowHost::InvalidateLayout() { - need_layout_ = true; - this->InvalidatePaint(); -} - -bool WindowHost::IsLayoutPreferToFillWindow() const { - return layout_prefer_to_fill_window_; -} - -void WindowHost::SetLayoutPreferToFillWindow(bool value) { - if (value == layout_prefer_to_fill_window_) return; - layout_prefer_to_fill_window_ = value; - InvalidateLayout(); -} - -void WindowHost::Relayout() { - const auto available_size = - native_window_ ? native_window_->GetClientSize() - : Size{100, 100}; // a reasonable assumed size - Relayout(available_size); -} - -void WindowHost::Relayout(const Size& available_size) { - root_render_object_->Measure( - render::MeasureRequirement{available_size, - IsLayoutPreferToFillWindow() - ? render::MeasureSize(available_size) - : render::MeasureSize::NotSpecified()}, - render::MeasureSize::NotSpecified()); - root_render_object_->Layout(Point{}); - for (auto& action : after_layout_stable_action_) action(); - after_layout_event_.Raise(AfterLayoutEventArgs{}); - root_render_object_->TraverseDescendants( - [](render::RenderObject* render_object) { - render_object->OnAfterLayout(); - }); - after_layout_stable_action_.clear(); - if constexpr (debug_flags::layout) - log::TagDebug(log_tag, u"A relayout is finished."); -} - -Control* WindowHost::GetFocusControl() { return focus_control_; } - -void WindowHost::SetFocusControl(Control* control) { - if (focus_control_ == control) return; - if (control == nullptr) control = root_control_; - - const auto old_focus_control = focus_control_; - - focus_control_ = control; - - DispatchEvent(event_names::LoseFocus, old_focus_control, - &Control::LoseFocusEvent, nullptr, false); - - DispatchEvent(event_names::GainFocus, control, &Control::GainFocusEvent, - nullptr, false); -} - -bool WindowHost::CaptureMouseFor(Control* control) { - if (!native_window_) return false; - - if (control == mouse_captured_control_) return true; - - if (control == nullptr) { - const auto old_capture_control = mouse_captured_control_; - mouse_captured_control_ = - nullptr; // update this in case this is used in event handlers - if (old_capture_control != mouse_hover_control_) { - DispatchMouseHoverControlChangeEvent( - old_capture_control, mouse_hover_control_, - native_window_->GetMousePosition(), true, false); - } - UpdateCursor(); - return true; - } - - if (mouse_captured_control_) return false; - - mouse_captured_control_ = control; - DispatchMouseHoverControlChangeEvent( - mouse_hover_control_, mouse_captured_control_, - native_window_->GetMousePosition(), false, true); - UpdateCursor(); - return true; -} - -Control* WindowHost::GetMouseCaptureControl() { - return mouse_captured_control_; -} - -void WindowHost::RunAfterLayoutStable(std::function action) { - if (need_layout_) { - after_layout_stable_action_.push_back(std::move(action)); - } else { - action(); - } -} - -void WindowHost::OnNativeDestroy(INativeWindow* window, std::nullptr_t) { - CRU_UNUSED(window) - this->native_window_ = nullptr; -} - -void WindowHost::OnNativePaint(INativeWindow* window, std::nullptr_t) { - if (need_layout_) { - Relayout(); - need_layout_ = false; - } - auto painter = window->BeginPaint(); - painter->Clear(colors::white); - root_render_object_->Draw(painter.get()); - painter->EndDraw(); -} - -void WindowHost::OnNativeResize(INativeWindow* window, const Size& size) { - CRU_UNUSED(window) - CRU_UNUSED(size) - - InvalidateLayout(); -} - -void WindowHost::OnNativeFocus(INativeWindow* window, - platform::gui::FocusChangeType focus) { - CRU_UNUSED(window) - - focus == platform::gui::FocusChangeType::Gain - ? DispatchEvent(event_names::GainFocus, focus_control_, - &Control::GainFocusEvent, nullptr, true) - : DispatchEvent(event_names::LoseFocus, focus_control_, - &Control::LoseFocusEvent, nullptr, true); -} - -void WindowHost::OnNativeMouseEnterLeave( - INativeWindow* window, platform::gui::MouseEnterLeaveType type) { - CRU_UNUSED(window) - - if (type == platform::gui::MouseEnterLeaveType::Leave) { - DispatchEvent(event_names::MouseLeave, mouse_hover_control_, - &Control::MouseLeaveEvent, nullptr); - mouse_hover_control_ = nullptr; - } -} - -void WindowHost::OnNativeMouseMove(INativeWindow* window, const Point& point) { - CRU_UNUSED(window) - - // Find the first control that hit test succeed. - const auto new_mouse_hover_control = HitTest(point); - const auto old_mouse_hover_control = mouse_hover_control_; - mouse_hover_control_ = new_mouse_hover_control; - - if (mouse_captured_control_) { - const auto n = FindLowestCommonAncestor(new_mouse_hover_control, - mouse_captured_control_); - const auto o = FindLowestCommonAncestor(old_mouse_hover_control, - mouse_captured_control_); - bool a = IsAncestor(o, n); - if (a) { - DispatchEvent(event_names::MouseLeave, o, &Control::MouseLeaveEvent, n); - } else { - DispatchEvent(event_names::MouseEnter, n, &Control::MouseEnterEvent, o, - point); - } - DispatchEvent(event_names::MouseMove, mouse_captured_control_, - &Control::MouseMoveEvent, nullptr, point); - UpdateCursor(); - return; - } - - DispatchMouseHoverControlChangeEvent( - old_mouse_hover_control, new_mouse_hover_control, point, false, false); - DispatchEvent(event_names::MouseMove, new_mouse_hover_control, - &Control::MouseMoveEvent, nullptr, point); - UpdateCursor(); -} - -void WindowHost::OnNativeMouseDown( - INativeWindow* window, - const platform::gui::NativeMouseButtonEventArgs& args) { - CRU_UNUSED(window) - - Control* control = - mouse_captured_control_ ? mouse_captured_control_ : HitTest(args.point); - DispatchEvent(event_names::MouseDown, control, &Control::MouseDownEvent, - nullptr, args.point, args.button, args.modifier); -} - -void WindowHost::OnNativeMouseUp( - INativeWindow* window, - const platform::gui::NativeMouseButtonEventArgs& args) { - CRU_UNUSED(window) - - Control* control = - mouse_captured_control_ ? mouse_captured_control_ : HitTest(args.point); - DispatchEvent(event_names::MouseUp, control, &Control::MouseUpEvent, nullptr, - args.point, args.button, args.modifier); -} - -void WindowHost::OnNativeKeyDown( - INativeWindow* window, const platform::gui::NativeKeyEventArgs& args) { - CRU_UNUSED(window) - - DispatchEvent(event_names::KeyDown, focus_control_, &Control::KeyDownEvent, - nullptr, args.key, args.modifier); -} - -void WindowHost::OnNativeKeyUp(INativeWindow* window, - const platform::gui::NativeKeyEventArgs& args) { - CRU_UNUSED(window) - - DispatchEvent(event_names::KeyUp, focus_control_, &Control::KeyUpEvent, - nullptr, args.key, args.modifier); -} - -void WindowHost::DispatchMouseHoverControlChangeEvent(Control* old_control, - Control* new_control, - const Point& point, - bool no_leave, - bool no_enter) { - if (new_control != old_control) // if the mouse-hover-on control changed - { - const auto lowest_common_ancestor = - FindLowestCommonAncestor(old_control, new_control); - if (!no_leave && old_control != nullptr) - DispatchEvent(event_names::MouseLeave, old_control, - &Control::MouseLeaveEvent, - lowest_common_ancestor); // dispatch mouse leave event. - if (!no_enter && new_control != nullptr) { - DispatchEvent(event_names::MouseEnter, new_control, - &Control::MouseEnterEvent, lowest_common_ancestor, - point); // dispatch mouse enter event. - } - } -} - -void WindowHost::UpdateCursor() { - if (native_window_) { - const auto capture = GetMouseCaptureControl(); - native_window_->SetCursor( - (capture ? capture : GetMouseHoverControl())->GetInheritedCursor()); - } -} - -Control* WindowHost::HitTest(const Point& point) { - const auto render_object = root_render_object_->HitTest(point); - if (render_object) { - const auto control = render_object->GetAttachedControl(); - Ensures(control); - return control; - } - return root_control_; -} -} // namespace cru::ui diff --git a/src/ui/controls/TextControlService.hpp b/src/ui/controls/TextControlService.hpp index 8ad87416..a7e4e440 100644 --- a/src/ui/controls/TextControlService.hpp +++ b/src/ui/controls/TextControlService.hpp @@ -12,7 +12,7 @@ #include "cru/ui/DebugFlags.hpp" #include "cru/ui/ShortcutHub.hpp" #include "cru/ui/UiEvent.hpp" -#include "cru/ui/WindowHost.hpp" +#include "cru/ui/host/WindowHost.hpp" #include "cru/ui/render/CanvasRenderObject.hpp" #include "cru/ui/render/ScrollRenderObject.hpp" #include "cru/ui/render/TextRenderObject.hpp" @@ -136,7 +136,7 @@ class TextControlService : public Object { } platform::gui::IInputMethodContext* GetInputMethodContext() { - WindowHost* host = this->control_->GetWindowHost(); + host::WindowHost* host = this->control_->GetWindowHost(); if (!host) return nullptr; platform::gui::INativeWindow* native_window = host->GetNativeWindow(); if (!native_window) return nullptr; diff --git a/src/ui/host/RoutedEventDispatch.hpp b/src/ui/host/RoutedEventDispatch.hpp new file mode 100644 index 00000000..de94a598 --- /dev/null +++ b/src/ui/host/RoutedEventDispatch.hpp @@ -0,0 +1,110 @@ +#pragma once +#include "cru/ui/Control.hpp" + +#include "cru/common/Logger.hpp" +#include "cru/ui/DebugFlags.hpp" + +#include + +namespace cru::ui { +// Dispatch the event. +// +// This will raise routed event of the control and its parent and parent's +// parent ... (until "last_receiver" if it's not nullptr) with appropriate args. +// +// First tunnel from top to bottom possibly stopped by "handled" flag in +// EventArgs. Second bubble from bottom to top possibly stopped by "handled" +// flag in EventArgs. Last direct to each control. +// +// Args is of type "EventArgs". The first init argument is "sender", which is +// automatically bound to each receiving control. The second init argument is +// "original_sender", which is unchanged. And "args" will be perfectly forwarded +// as the rest arguments. +template +void DispatchEvent(const std::u16string_view& event_name, + Control* const original_sender, + event::RoutedEvent* (Control::*event_ptr)(), + Control* const last_receiver, Args&&... args) { + CRU_UNUSED(event_name) + + if (original_sender == last_receiver) { + if constexpr (debug_flags::routed_event) + log::Debug( + "Routed event {} no need to dispatch (original_sender == " + "last_receiver). Original sender is {}.", + event_name, original_sender->GetControlType()); + return; + } + + std::vector receive_list; + + auto parent = original_sender; + while (parent != last_receiver) { + receive_list.push_back(parent); + parent = parent->GetParent(); + } + + if constexpr (debug_flags::routed_event) { + std::u16string log = u"Dispatch routed event "; + log += event_name; + log += u". Path (parent first): "; + auto i = receive_list.crbegin(); + const auto end = --receive_list.crend(); + for (; i != end; ++i) { + log += (*i)->GetControlType(); + log += u" -> "; + } + log += (*i)->GetControlType(); + log::Debug(log); + } + + auto handled = false; + + int count = 0; + + // tunnel + for (auto i = receive_list.crbegin(); i != receive_list.crend(); ++i) { + count++; + EventArgs event_args(*i, original_sender, std::forward(args)...); + static_cast*>(((*i)->*event_ptr)()->Tunnel()) + ->Raise(event_args); + if (event_args.IsHandled()) { + handled = true; + if constexpr (debug_flags::routed_event) + log::Debug( + u"Routed event is short-circuit in TUNNEL at {}-st control (count " + u"from parent).", + count); + break; + } + } + + // bubble + if (!handled) { + for (auto i : receive_list) { + count--; + EventArgs event_args(i, original_sender, std::forward(args)...); + static_cast*>((i->*event_ptr)()->Bubble()) + ->Raise(event_args); + if (event_args.IsHandled()) { + if constexpr (debug_flags::routed_event) + log::Debug( + u"Routed event is short-circuit in BUBBLE at {}-st control " + u"(count from parent).", + count); + break; + } + } + } + + // direct + for (auto i : receive_list) { + EventArgs event_args(i, original_sender, std::forward(args)...); + static_cast*>((i->*event_ptr)()->Direct()) + ->Raise(event_args); + } + + if constexpr (debug_flags::routed_event) + log::Debug(u"Routed event dispatch finished."); +} +} // namespace cru::ui diff --git a/src/ui/host/WindowHost.cpp b/src/ui/host/WindowHost.cpp new file mode 100644 index 00000000..eac247c1 --- /dev/null +++ b/src/ui/host/WindowHost.cpp @@ -0,0 +1,400 @@ +#include "cru/ui/host/WindowHost.hpp" + +#include "RoutedEventDispatch.hpp" +#include "cru/common/Logger.hpp" +#include "cru/platform/graphics/Painter.hpp" +#include "cru/platform/gui/InputMethod.hpp" +#include "cru/platform/gui/UiApplication.hpp" +#include "cru/platform/gui/Window.hpp" +#include "cru/ui/DebugFlags.hpp" +#include "cru/ui/Window.hpp" +#include "cru/ui/render/MeasureRequirement.hpp" +#include "cru/ui/render/RenderObject.hpp" + +#include + +namespace cru::ui::host { +using platform::gui::INativeWindow; +using platform::gui::IUiApplication; + +namespace event_names { +#ifdef CRU_DEBUG +// clang-format off +#define CRU_DEFINE_EVENT_NAME(name) constexpr const char16_t* name = CRU_MAKE_UNICODE_LITERAL(name); +// clang-format on +#else +#define CRU_DEFINE_EVENT_NAME(name) constexpr const char16_t* name = u""; +#endif + +CRU_DEFINE_EVENT_NAME(LoseFocus) +CRU_DEFINE_EVENT_NAME(GainFocus) +CRU_DEFINE_EVENT_NAME(MouseEnter) +CRU_DEFINE_EVENT_NAME(MouseLeave) +CRU_DEFINE_EVENT_NAME(MouseMove) +CRU_DEFINE_EVENT_NAME(MouseDown) +CRU_DEFINE_EVENT_NAME(MouseUp) +CRU_DEFINE_EVENT_NAME(KeyDown) +CRU_DEFINE_EVENT_NAME(KeyUp) + +#undef CRU_DEFINE_EVENT_NAME +} // namespace event_names + +namespace { +bool IsAncestor(Control* control, Control* ancestor) { + while (control != nullptr) { + if (control == ancestor) return true; + control = control->GetParent(); + } + return false; +} + +// Ancestor at last. +std::vector GetAncestorList(Control* control) { + std::vector l; + while (control != nullptr) { + l.push_back(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.back() != right_list.back()) return nullptr; + + // find the last same control or the last control (one is ancestor of the + // other) + auto left_iter = left_list.crbegin(); + auto right_iter = right_list.crbegin(); + + while (true) { + if (left_iter == left_list.crend()) { + return left_list.front(); + } + if (right_iter == right_list.crend()) { + return right_list.front(); + } + if (*left_iter != *right_iter) { + return *(--left_iter); + } + ++left_iter; + ++right_iter; + } +} +} // namespace + +namespace { +template +inline void BindNativeEvent( + WindowHost* host, INativeWindow* native_window, IEvent* event, + void (WindowHost::*handler)(INativeWindow*, typename IEvent::EventArgs), + std::vector& guard_pool) { + guard_pool.push_back(EventRevokerGuard(event->AddHandler( + std::bind(handler, host, native_window, std::placeholders::_1)))); +} +} // namespace + +WindowHost::WindowHost(Control* root_control) + : root_control_(root_control), focus_control_(root_control) { + const auto ui_application = IUiApplication::GetInstance(); + auto native_window = ui_application->CreateWindow(nullptr); + native_window_ = native_window; + + root_control_->TraverseDescendants([this](Control* control) { + control->window_host_ = this; + control->OnAttachToHost(this); + }); + + root_render_object_ = root_control->GetRenderObject(); + root_render_object_->SetWindowHostRecursive(this); + + BindNativeEvent(this, native_window, native_window->DestroyEvent(), + &WindowHost::OnNativeDestroy, event_revoker_guards_); + BindNativeEvent(this, native_window, native_window->PaintEvent(), + &WindowHost::OnNativePaint, event_revoker_guards_); + BindNativeEvent(this, native_window, native_window->ResizeEvent(), + &WindowHost::OnNativeResize, event_revoker_guards_); + BindNativeEvent(this, native_window, native_window->FocusEvent(), + &WindowHost::OnNativeFocus, event_revoker_guards_); + BindNativeEvent(this, native_window, native_window->MouseEnterLeaveEvent(), + &WindowHost::OnNativeMouseEnterLeave, event_revoker_guards_); + BindNativeEvent(this, native_window, native_window->MouseMoveEvent(), + &WindowHost::OnNativeMouseMove, event_revoker_guards_); + BindNativeEvent(this, native_window, native_window->MouseDownEvent(), + &WindowHost::OnNativeMouseDown, event_revoker_guards_); + BindNativeEvent(this, native_window, native_window->MouseUpEvent(), + &WindowHost::OnNativeMouseUp, event_revoker_guards_); + BindNativeEvent(this, native_window, native_window->KeyDownEvent(), + &WindowHost::OnNativeKeyDown, event_revoker_guards_); + BindNativeEvent(this, native_window, native_window->KeyUpEvent(), + &WindowHost::OnNativeKeyUp, event_revoker_guards_); +} + +WindowHost::~WindowHost() { + if (native_window_) { + native_window_->Close(); + } +} + +void WindowHost::InvalidatePaint() { + if (native_window_) native_window_->RequestRepaint(); +} + +void WindowHost::InvalidateLayout() { + need_layout_ = true; + this->InvalidatePaint(); +} + +bool WindowHost::IsLayoutPreferToFillWindow() const { + return layout_prefer_to_fill_window_; +} + +void WindowHost::SetLayoutPreferToFillWindow(bool value) { + if (value == layout_prefer_to_fill_window_) return; + layout_prefer_to_fill_window_ = value; + InvalidateLayout(); +} + +void WindowHost::Relayout() { + const auto available_size = + native_window_ ? native_window_->GetClientSize() + : Size{100, 100}; // a reasonable assumed size + Relayout(available_size); +} + +void WindowHost::Relayout(const Size& available_size) { + root_render_object_->Measure( + render::MeasureRequirement{available_size, + IsLayoutPreferToFillWindow() + ? render::MeasureSize(available_size) + : render::MeasureSize::NotSpecified()}, + render::MeasureSize::NotSpecified()); + root_render_object_->Layout(Point{}); + for (auto& action : after_layout_stable_action_) action(); + after_layout_event_.Raise(AfterLayoutEventArgs{}); + root_render_object_->TraverseDescendants( + [](render::RenderObject* render_object) { + render_object->OnAfterLayout(); + }); + after_layout_stable_action_.clear(); + if constexpr (debug_flags::layout) + log::TagDebug(log_tag, u"A relayout is finished."); +} + +Control* WindowHost::GetFocusControl() { return focus_control_; } + +void WindowHost::SetFocusControl(Control* control) { + if (focus_control_ == control) return; + if (control == nullptr) control = root_control_; + + const auto old_focus_control = focus_control_; + + focus_control_ = control; + + DispatchEvent(event_names::LoseFocus, old_focus_control, + &Control::LoseFocusEvent, nullptr, false); + + DispatchEvent(event_names::GainFocus, control, &Control::GainFocusEvent, + nullptr, false); +} + +bool WindowHost::CaptureMouseFor(Control* control) { + if (!native_window_) return false; + + if (control == mouse_captured_control_) return true; + + if (control == nullptr) { + const auto old_capture_control = mouse_captured_control_; + mouse_captured_control_ = + nullptr; // update this in case this is used in event handlers + if (old_capture_control != mouse_hover_control_) { + DispatchMouseHoverControlChangeEvent( + old_capture_control, mouse_hover_control_, + native_window_->GetMousePosition(), true, false); + } + UpdateCursor(); + return true; + } + + if (mouse_captured_control_) return false; + + mouse_captured_control_ = control; + DispatchMouseHoverControlChangeEvent( + mouse_hover_control_, mouse_captured_control_, + native_window_->GetMousePosition(), false, true); + UpdateCursor(); + return true; +} + +Control* WindowHost::GetMouseCaptureControl() { + return mouse_captured_control_; +} + +void WindowHost::RunAfterLayoutStable(std::function action) { + if (need_layout_) { + after_layout_stable_action_.push_back(std::move(action)); + } else { + action(); + } +} + +void WindowHost::OnNativeDestroy(INativeWindow* window, std::nullptr_t) { + CRU_UNUSED(window) + this->native_window_ = nullptr; +} + +void WindowHost::OnNativePaint(INativeWindow* window, std::nullptr_t) { + if (need_layout_) { + Relayout(); + need_layout_ = false; + } + auto painter = window->BeginPaint(); + painter->Clear(colors::white); + root_render_object_->Draw(painter.get()); + painter->EndDraw(); +} + +void WindowHost::OnNativeResize(INativeWindow* window, const Size& size) { + CRU_UNUSED(window) + CRU_UNUSED(size) + + InvalidateLayout(); +} + +void WindowHost::OnNativeFocus(INativeWindow* window, + platform::gui::FocusChangeType focus) { + CRU_UNUSED(window) + + focus == platform::gui::FocusChangeType::Gain + ? DispatchEvent(event_names::GainFocus, focus_control_, + &Control::GainFocusEvent, nullptr, true) + : DispatchEvent(event_names::LoseFocus, focus_control_, + &Control::LoseFocusEvent, nullptr, true); +} + +void WindowHost::OnNativeMouseEnterLeave( + INativeWindow* window, platform::gui::MouseEnterLeaveType type) { + CRU_UNUSED(window) + + if (type == platform::gui::MouseEnterLeaveType::Leave) { + DispatchEvent(event_names::MouseLeave, mouse_hover_control_, + &Control::MouseLeaveEvent, nullptr); + mouse_hover_control_ = nullptr; + } +} + +void WindowHost::OnNativeMouseMove(INativeWindow* window, const Point& point) { + CRU_UNUSED(window) + + // Find the first control that hit test succeed. + const auto new_mouse_hover_control = HitTest(point); + const auto old_mouse_hover_control = mouse_hover_control_; + mouse_hover_control_ = new_mouse_hover_control; + + if (mouse_captured_control_) { + const auto n = FindLowestCommonAncestor(new_mouse_hover_control, + mouse_captured_control_); + const auto o = FindLowestCommonAncestor(old_mouse_hover_control, + mouse_captured_control_); + bool a = IsAncestor(o, n); + if (a) { + DispatchEvent(event_names::MouseLeave, o, &Control::MouseLeaveEvent, n); + } else { + DispatchEvent(event_names::MouseEnter, n, &Control::MouseEnterEvent, o, + point); + } + DispatchEvent(event_names::MouseMove, mouse_captured_control_, + &Control::MouseMoveEvent, nullptr, point); + UpdateCursor(); + return; + } + + DispatchMouseHoverControlChangeEvent( + old_mouse_hover_control, new_mouse_hover_control, point, false, false); + DispatchEvent(event_names::MouseMove, new_mouse_hover_control, + &Control::MouseMoveEvent, nullptr, point); + UpdateCursor(); +} + +void WindowHost::OnNativeMouseDown( + INativeWindow* window, + const platform::gui::NativeMouseButtonEventArgs& args) { + CRU_UNUSED(window) + + Control* control = + mouse_captured_control_ ? mouse_captured_control_ : HitTest(args.point); + DispatchEvent(event_names::MouseDown, control, &Control::MouseDownEvent, + nullptr, args.point, args.button, args.modifier); +} + +void WindowHost::OnNativeMouseUp( + INativeWindow* window, + const platform::gui::NativeMouseButtonEventArgs& args) { + CRU_UNUSED(window) + + Control* control = + mouse_captured_control_ ? mouse_captured_control_ : HitTest(args.point); + DispatchEvent(event_names::MouseUp, control, &Control::MouseUpEvent, nullptr, + args.point, args.button, args.modifier); +} + +void WindowHost::OnNativeKeyDown( + INativeWindow* window, const platform::gui::NativeKeyEventArgs& args) { + CRU_UNUSED(window) + + DispatchEvent(event_names::KeyDown, focus_control_, &Control::KeyDownEvent, + nullptr, args.key, args.modifier); +} + +void WindowHost::OnNativeKeyUp(INativeWindow* window, + const platform::gui::NativeKeyEventArgs& args) { + CRU_UNUSED(window) + + DispatchEvent(event_names::KeyUp, focus_control_, &Control::KeyUpEvent, + nullptr, args.key, args.modifier); +} + +void WindowHost::DispatchMouseHoverControlChangeEvent(Control* old_control, + Control* new_control, + const Point& point, + bool no_leave, + bool no_enter) { + if (new_control != old_control) // if the mouse-hover-on control changed + { + const auto lowest_common_ancestor = + FindLowestCommonAncestor(old_control, new_control); + if (!no_leave && old_control != nullptr) + DispatchEvent(event_names::MouseLeave, old_control, + &Control::MouseLeaveEvent, + lowest_common_ancestor); // dispatch mouse leave event. + if (!no_enter && new_control != nullptr) { + DispatchEvent(event_names::MouseEnter, new_control, + &Control::MouseEnterEvent, lowest_common_ancestor, + point); // dispatch mouse enter event. + } + } +} + +void WindowHost::UpdateCursor() { + if (native_window_) { + const auto capture = GetMouseCaptureControl(); + native_window_->SetCursor( + (capture ? capture : GetMouseHoverControl())->GetInheritedCursor()); + } +} + +Control* WindowHost::HitTest(const Point& point) { + const auto render_object = root_render_object_->HitTest(point); + if (render_object) { + const auto control = render_object->GetAttachedControl(); + Ensures(control); + return control; + } + return root_control_; +} +} // namespace cru::ui diff --git a/src/ui/render/RenderObject.cpp b/src/ui/render/RenderObject.cpp index 09410113..a40ce9b8 100644 --- a/src/ui/render/RenderObject.cpp +++ b/src/ui/render/RenderObject.cpp @@ -3,7 +3,7 @@ #include "cru/common/Logger.hpp" #include "cru/platform/graphics/util/Painter.hpp" #include "cru/ui/DebugFlags.hpp" -#include "cru/ui/WindowHost.hpp" +#include "cru/ui/host/WindowHost.hpp" #include #include @@ -303,7 +303,7 @@ std::u16string RenderObject::GetDebugPathInTree() const { return result; } -void RenderObject::SetWindowHostRecursive(WindowHost* host) { +void RenderObject::SetWindowHostRecursive(host::WindowHost* host) { if (window_host_ != nullptr) { detach_from_host_event_.Raise(nullptr); } -- cgit v1.2.3 From 2188845a7acffa653015a1000139ec0a9a3984bc Mon Sep 17 00:00:00 2001 From: crupest Date: Sun, 8 Nov 2020 17:45:41 +0800 Subject: ... --- demos/main/main.cpp | 6 +- include/cru/platform/gui/UiApplication.hpp | 19 ++- include/cru/ui/Base.hpp | 4 +- include/cru/ui/ClickDetector.hpp | 87 ----------- include/cru/ui/ContentControl.hpp | 26 ---- include/cru/ui/Control.hpp | 151 ------------------- include/cru/ui/LayoutControl.hpp | 19 --- include/cru/ui/NoChildControl.hpp | 20 --- include/cru/ui/ShortcutHub.hpp | 130 ---------------- include/cru/ui/UiEvent.hpp | 228 ----------------------------- include/cru/ui/Window.hpp | 36 ----- include/cru/ui/controls/Base.hpp | 10 +- include/cru/ui/controls/Button.hpp | 7 +- include/cru/ui/controls/Container.hpp | 2 +- include/cru/ui/controls/ContentControl.hpp | 26 ++++ include/cru/ui/controls/Control.hpp | 151 +++++++++++++++++++ include/cru/ui/controls/FlexLayout.hpp | 2 +- include/cru/ui/controls/LayoutControl.hpp | 19 +++ include/cru/ui/controls/NoChildControl.hpp | 20 +++ include/cru/ui/controls/StackLayout.hpp | 2 +- include/cru/ui/controls/TextBlock.hpp | 2 +- include/cru/ui/controls/TextBox.hpp | 3 +- include/cru/ui/controls/Window.hpp | 36 +++++ include/cru/ui/events/UiEvent.hpp | 228 +++++++++++++++++++++++++++++ include/cru/ui/helper/ClickDetector.hpp | 87 +++++++++++ include/cru/ui/helper/ShortcutHub.hpp | 129 ++++++++++++++++ include/cru/ui/host/WindowHost.hpp | 50 +++---- include/cru/ui/render/RenderObject.hpp | 12 +- include/cru/win/gui/UiApplication.hpp | 2 +- src/ui/CMakeLists.txt | 32 ++-- src/ui/ClickDetector.cpp | 131 ----------------- src/ui/ContentControl.cpp | 27 ---- src/ui/Control.cpp | 157 -------------------- src/ui/LayoutControl.cpp | 6 - src/ui/NoChildControl.cpp | 3 - src/ui/ShortcutHub.cpp | 120 --------------- src/ui/UiEvent.cpp | 10 -- src/ui/Window.cpp | 32 ---- src/ui/controls/Button.cpp | 17 +-- src/ui/controls/ContentControl.cpp | 25 ++++ src/ui/controls/Control.cpp | 157 ++++++++++++++++++++ src/ui/controls/LayoutControl.cpp | 3 + src/ui/controls/NoChildControl.cpp | 3 + src/ui/controls/TextControlService.hpp | 8 +- src/ui/controls/Window.cpp | 32 ++++ src/ui/events/UiEvent.cpp | 10 ++ src/ui/helper/ClickDetector.cpp | 131 +++++++++++++++++ src/ui/helper/ShortcutHub.cpp | 120 +++++++++++++++ src/ui/host/RoutedEventDispatch.hpp | 14 +- src/ui/host/WindowHost.cpp | 83 ++++++----- src/win/gui/UiApplication.cpp | 12 +- 51 files changed, 1333 insertions(+), 1314 deletions(-) delete mode 100644 include/cru/ui/ClickDetector.hpp delete mode 100644 include/cru/ui/ContentControl.hpp delete mode 100644 include/cru/ui/Control.hpp delete mode 100644 include/cru/ui/LayoutControl.hpp delete mode 100644 include/cru/ui/NoChildControl.hpp delete mode 100644 include/cru/ui/ShortcutHub.hpp delete mode 100644 include/cru/ui/UiEvent.hpp delete mode 100644 include/cru/ui/Window.hpp create mode 100644 include/cru/ui/controls/ContentControl.hpp create mode 100644 include/cru/ui/controls/Control.hpp create mode 100644 include/cru/ui/controls/LayoutControl.hpp create mode 100644 include/cru/ui/controls/NoChildControl.hpp create mode 100644 include/cru/ui/controls/Window.hpp create mode 100644 include/cru/ui/events/UiEvent.hpp create mode 100644 include/cru/ui/helper/ClickDetector.hpp create mode 100644 include/cru/ui/helper/ShortcutHub.hpp delete mode 100644 src/ui/ClickDetector.cpp delete mode 100644 src/ui/ContentControl.cpp delete mode 100644 src/ui/Control.cpp delete mode 100644 src/ui/LayoutControl.cpp delete mode 100644 src/ui/NoChildControl.cpp delete mode 100644 src/ui/ShortcutHub.cpp delete mode 100644 src/ui/UiEvent.cpp delete mode 100644 src/ui/Window.cpp create mode 100644 src/ui/controls/ContentControl.cpp create mode 100644 src/ui/controls/Control.cpp create mode 100644 src/ui/controls/LayoutControl.cpp create mode 100644 src/ui/controls/NoChildControl.cpp create mode 100644 src/ui/controls/Window.cpp create mode 100644 src/ui/events/UiEvent.cpp create mode 100644 src/ui/helper/ClickDetector.cpp create mode 100644 src/ui/helper/ShortcutHub.cpp (limited to 'demos/main/main.cpp') diff --git a/demos/main/main.cpp b/demos/main/main.cpp index 5546f3dd..dd3e31e9 100644 --- a/demos/main/main.cpp +++ b/demos/main/main.cpp @@ -2,19 +2,19 @@ #include "cru/platform/gui/UiApplication.hpp" #include "cru/platform/gui/Window.hpp" #include "cru/ui/Base.hpp" -#include "cru/ui/Window.hpp" -#include "cru/ui/host/WindowHost.hpp" #include "cru/ui/controls/Button.hpp" #include "cru/ui/controls/FlexLayout.hpp" #include "cru/ui/controls/TextBlock.hpp" #include "cru/ui/controls/TextBox.hpp" +#include "cru/ui/controls/Window.hpp" +#include "cru/ui/host/WindowHost.hpp" using cru::platform::gui::CreateUiApplication; -using cru::ui::Window; using cru::ui::controls::Button; using cru::ui::controls::FlexLayout; using cru::ui::controls::TextBlock; using cru::ui::controls::TextBox; +using cru::ui::controls::Window; int main() { #ifdef CRU_DEBUG diff --git a/include/cru/platform/gui/UiApplication.hpp b/include/cru/platform/gui/UiApplication.hpp index ff947dfc..ba85020a 100644 --- a/include/cru/platform/gui/UiApplication.hpp +++ b/include/cru/platform/gui/UiApplication.hpp @@ -1,12 +1,24 @@ #pragma once #include "Base.hpp" +#include "cru/common/Bitmask.hpp" + #include #include #include #include namespace cru::platform::gui { +namespace details { +struct CreateWindowFlagTag; +} + +using CreateWindowFlag = Bitmask; + +struct CreateWindowFlags { + static constexpr CreateWindowFlag NoCaptionAndBorder{0b1}; +}; + // The entry point of a ui application. struct IUiApplication : public virtual INativeResource { public: @@ -43,7 +55,12 @@ struct IUiApplication : public virtual INativeResource { virtual void CancelTimer(long long id) = 0; virtual std::vector GetAllWindow() = 0; - virtual INativeWindow* CreateWindow(INativeWindow* parent) = 0; + + INativeWindow* CreateWindow(INativeWindow* parent) { + return this->CreateWindow(parent, CreateWindowFlag(0)); + }; + virtual INativeWindow* CreateWindow(INativeWindow* parent, + CreateWindowFlag flags) = 0; virtual cru::platform::graphics::IGraphFactory* GetGraphFactory() = 0; diff --git a/include/cru/ui/Base.hpp b/include/cru/ui/Base.hpp index 39fbb035..8595258d 100644 --- a/include/cru/ui/Base.hpp +++ b/include/cru/ui/Base.hpp @@ -26,9 +26,11 @@ namespace mouse_buttons = cru::platform::gui::mouse_buttons; namespace colors = cru::platform::colors; //-------------------- region: forward declaration -------------------- + +namespace controls { class Window; class Control; -class ClickDetector; +} // namespace controls namespace host { class WindowHost; diff --git a/include/cru/ui/ClickDetector.hpp b/include/cru/ui/ClickDetector.hpp deleted file mode 100644 index 4ffe5d05..00000000 --- a/include/cru/ui/ClickDetector.hpp +++ /dev/null @@ -1,87 +0,0 @@ -#pragma once -#include "Control.hpp" - -namespace cru::ui { -class ClickEventArgs : Object { - public: - ClickEventArgs(Control* sender, const Point& down_point, - const Point& up_point, MouseButton button) - : sender_(sender), - down_point_(down_point), - up_point_(up_point), - button_(button) {} - - CRU_DEFAULT_COPY(ClickEventArgs) - CRU_DEFAULT_MOVE(ClickEventArgs) - - ~ClickEventArgs() override = default; - - Control* GetSender() const { return sender_; } - Point GetDownPoint() const { return down_point_; } - Point GetUpPoint() const { return up_point_; } - MouseButton GetButton() const { return button_; } - - private: - Control* sender_; - Point down_point_; - Point up_point_; - MouseButton button_; -}; - -enum class ClickState { - None, // Mouse is outside the control. - Hover, // Mouse hovers on the control but not pressed - Press, // Mouse is pressed and if released click is done. - PressInactive // Mouse is pressed but if released click is canceled. -}; - -class ClickDetector : public Object { - CRU_DEFINE_CLASS_LOG_TAG(u"cru::ui::ClickDetector") - - public: - explicit ClickDetector(Control* control); - - CRU_DELETE_COPY(ClickDetector) - CRU_DELETE_MOVE(ClickDetector) - - ~ClickDetector() override = default; - - Control* GetControl() const { return control_; } - - ClickState GetState() const { return state_; } - - // Default is enable. - bool IsEnabled() const { return enable_; } - // If disable when user is pressing, the pressing is deactivated. - void SetEnabled(bool enable); - - // Default is left and right. - MouseButton GetTriggerButton() const { return trigger_button_; } - // If unset the trigger button when user is pressing, the pressing is - // deactivated. - void SetTriggerButton(MouseButton trigger_button); - - IEvent* ClickEvent() { return &event_; } - - IEvent* StateChangeEvent() { return &state_change_event_; } - - private: - void SetState(ClickState state); - - private: - Control* control_; - - ClickState state_; - - bool enable_ = true; - MouseButton trigger_button_ = mouse_buttons::left | mouse_buttons::right; - - Event event_; - Event state_change_event_; - - std::vector event_rovoker_guards_; - - Point down_point_; - MouseButton button_; -}; -} // namespace cru::ui diff --git a/include/cru/ui/ContentControl.hpp b/include/cru/ui/ContentControl.hpp deleted file mode 100644 index ba5b6b2f..00000000 --- a/include/cru/ui/ContentControl.hpp +++ /dev/null @@ -1,26 +0,0 @@ -#pragma once -#include "Control.hpp" - -namespace cru::ui { -class ContentControl : public Control { - protected: - ContentControl() = default; - - public: - ContentControl(const ContentControl& other) = delete; - ContentControl(ContentControl&& other) = delete; - ContentControl& operator=(const ContentControl& other) = delete; - ContentControl& operator=(ContentControl&& other) = delete; - ~ContentControl() override = default; - - Control* GetChild() const; - void SetChild(Control* child); - - protected: - virtual void OnChildChanged(Control* old_child, Control* new_child); - - private: - using Control::AddChild; - using Control::RemoveChild; -}; -} // namespace cru::ui diff --git a/include/cru/ui/Control.hpp b/include/cru/ui/Control.hpp deleted file mode 100644 index fe50624a..00000000 --- a/include/cru/ui/Control.hpp +++ /dev/null @@ -1,151 +0,0 @@ -#pragma once -#include "Base.hpp" - -#include "UiEvent.hpp" -#include "cru/common/Event.hpp" -#include "render/Base.hpp" - -#include - -namespace cru::ui { -class Control : public Object { - friend host::WindowHost; - - protected: - Control(); - - public: - Control(const Control& other) = delete; - Control(Control&& other) = delete; - Control& operator=(const Control& other) = delete; - Control& operator=(Control&& other) = delete; - ~Control() override; - - public: - virtual std::u16string_view GetControlType() const = 0; - - //*************** region: tree *************** - public: - host::WindowHost* GetWindowHost() const; - - Control* GetParent() const { return parent_; } - - const std::vector& GetChildren() const { return children_; } - - // Traverse the tree rooted the control including itself. - void TraverseDescendants(const std::function& predicate); - - public: - virtual render::RenderObject* GetRenderObject() const = 0; - - //*************** region: focus *************** - public: - bool HasFocus(); - - void SetFocus(); - - //*************** region: mouse *************** - public: - bool IsMouseOver() const { return is_mouse_over_; } - - bool CaptureMouse(); - - bool ReleaseMouse(); - - bool IsMouseCaptured(); - - //*************** region: cursor *************** - // Cursor is inherited from parent recursively if not set. - public: - // null for not set - std::shared_ptr GetCursor(); - - // will not return nullptr - std::shared_ptr GetInheritedCursor(); - - // null to unset - void SetCursor(std::shared_ptr cursor); - - //*************** region: events *************** - public: - // Raised when mouse enter the control. Even when the control itself captures - // the mouse, this event is raised as regular. But if mouse is captured by - // another control, the control will not receive any mouse enter event. You - // can use `IsMouseCaptured` to get more info. - event::RoutedEvent* MouseEnterEvent() { - return &mouse_enter_event_; - } - // Raised when mouse is leave the control. Even when the control itself - // captures the mouse, this event is raised as regular. But if mouse is - // captured by another control, the control will not receive any mouse leave - // event. You can use `IsMouseCaptured` to get more info. - event::RoutedEvent* MouseLeaveEvent() { - return &mouse_leave_event_; - } - // Raised when mouse is move in the control. - event::RoutedEvent* MouseMoveEvent() { - return &mouse_move_event_; - } - // Raised when a mouse button is pressed in the control. - event::RoutedEvent* MouseDownEvent() { - return &mouse_down_event_; - } - // Raised when a mouse button is released in the control. - event::RoutedEvent* MouseUpEvent() { - return &mouse_up_event_; - } - event::RoutedEvent* MouseWheelEvent() { - return &mouse_wheel_event_; - } - event::RoutedEvent* KeyDownEvent() { - return &key_down_event_; - } - event::RoutedEvent* KeyUpEvent() { - return &key_up_event_; - } - event::RoutedEvent* GainFocusEvent() { - return &gain_focus_event_; - } - event::RoutedEvent* LoseFocusEvent() { - return &lose_focus_event_; - } - - private: - event::RoutedEvent mouse_enter_event_; - event::RoutedEvent mouse_leave_event_; - event::RoutedEvent mouse_move_event_; - event::RoutedEvent mouse_down_event_; - event::RoutedEvent mouse_up_event_; - event::RoutedEvent mouse_wheel_event_; - - event::RoutedEvent key_down_event_; - event::RoutedEvent key_up_event_; - - event::RoutedEvent gain_focus_event_; - event::RoutedEvent lose_focus_event_; - - //*************** region: tree *************** - protected: - void AddChild(Control* control, Index position); - void RemoveChild(Index position); - virtual void OnAddChild(Control* child, Index position); - virtual void OnRemoveChild(Control* child, Index position); - virtual void OnParentChanged(Control* old_parent, Control* new_parent); - virtual void OnAttachToHost(host::WindowHost* host); - virtual void OnDetachFromHost(host::WindowHost* host); - - protected: - virtual void OnMouseHoverChange(bool newHover) { CRU_UNUSED(newHover) } - - private: - Control* parent_ = nullptr; - std::vector children_; - - host::WindowHost* window_host_ = nullptr; - - private: - bool is_mouse_over_ = false; - - std::shared_ptr cursor_ = nullptr; -}; -} // namespace cru::ui diff --git a/include/cru/ui/LayoutControl.hpp b/include/cru/ui/LayoutControl.hpp deleted file mode 100644 index 69d5cd0b..00000000 --- a/include/cru/ui/LayoutControl.hpp +++ /dev/null @@ -1,19 +0,0 @@ -#pragma once -#include "Control.hpp" - -namespace cru::ui { -class LayoutControl : public Control { - protected: - LayoutControl() = default; - - public: - LayoutControl(const LayoutControl& other) = delete; - LayoutControl(LayoutControl&& other) = delete; - LayoutControl& operator=(const LayoutControl& other) = delete; - LayoutControl& operator=(LayoutControl&& other) = delete; - ~LayoutControl() override = default; - - using Control::AddChild; - using Control::RemoveChild; -}; -} // namespace cru::ui diff --git a/include/cru/ui/NoChildControl.hpp b/include/cru/ui/NoChildControl.hpp deleted file mode 100644 index 0d8a8e34..00000000 --- a/include/cru/ui/NoChildControl.hpp +++ /dev/null @@ -1,20 +0,0 @@ -#pragma once -#include "Control.hpp" - -namespace cru::ui { -class NoChildControl : public Control { - protected: - NoChildControl() = default; - - public: - NoChildControl(const NoChildControl& other) = delete; - NoChildControl(NoChildControl&& other) = delete; - NoChildControl& operator=(const NoChildControl& other) = delete; - NoChildControl& operator=(NoChildControl&& other) = delete; - ~NoChildControl() override = default; - - private: - using Control::AddChild; - using Control::RemoveChild; -}; -} // namespace cru::ui diff --git a/include/cru/ui/ShortcutHub.hpp b/include/cru/ui/ShortcutHub.hpp deleted file mode 100644 index 1145c661..00000000 --- a/include/cru/ui/ShortcutHub.hpp +++ /dev/null @@ -1,130 +0,0 @@ -#pragma once -#include "Base.hpp" - -#include "cru/common/Base.hpp" -#include "cru/common/Event.hpp" -#include "cru/platform/gui/Keyboard.hpp" -#include "cru/ui/UiEvent.hpp" - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace cru::ui { - -class ShortcutKeyBind { - public: - ShortcutKeyBind(platform::gui::KeyCode key, - platform::gui::KeyModifier modifier) - : key_(key), modifier_(modifier) {} - - CRU_DEFAULT_COPY(ShortcutKeyBind) - CRU_DEFAULT_MOVE(ShortcutKeyBind) - - ~ShortcutKeyBind() = default; - - platform::gui::KeyCode GetKey() const { return key_; } - platform::gui::KeyModifier GetModifier() const { return modifier_; } - - bool Is(platform::gui::KeyCode key, - platform::gui::KeyModifier modifier) const { - return key == key_ && modifier == modifier_; - } - - bool operator==(const ShortcutKeyBind& other) const { - return this->key_ == other.key_ && this->modifier_ == other.modifier_; - } - - bool operator!=(const ShortcutKeyBind& other) const { - return !this->operator==(other); - } - - std::u16string ToString() { - std::u16string result = u"("; - result += platform::gui::ToString(modifier_); - result += u")"; - result += platform::gui::ToString(key_); - return result; - } - - private: - platform::gui::KeyCode key_; - platform::gui::KeyModifier modifier_; -}; -} // namespace cru::ui - -namespace std { -template <> -struct hash { - std::size_t operator()(const cru::ui::ShortcutKeyBind& value) const { - std::size_t result = 0; - cru::hash_combine(result, static_cast(value.GetKey())); - cru::hash_combine(result, static_cast(value.GetModifier())); - return result; - } -}; -} // namespace std - -namespace cru::ui { -struct Shortcut { - // Just for debug. - std::u16string name; - ShortcutKeyBind key_bind; - // Return true if it consumes the shortcut. Or return false if it does not - // handle the shortcut. - std::function handler; -}; - -struct ShortcutInfo { - int id; - std::u16string name; - ShortcutKeyBind key_bind; - std::function handler; -}; - -class ShortcutHub : public Object { - public: - ShortcutHub() = default; - - CRU_DELETE_COPY(ShortcutHub) - CRU_DELETE_MOVE(ShortcutHub) - - ~ShortcutHub() override = default; - - int RegisterShortcut(std::u16string name, ShortcutKeyBind bind, - std::function handler) { - return RegisterShortcut({std::move(name), bind, std::move(handler)}); - } - - // Return an id used for unregistering. - int RegisterShortcut(Shortcut shortcut); - - void UnregisterShortcut(int id); - - std::vector GetAllShortcuts() const; - std::optional GetShortcut(int id) const; - const std::vector& GetShortcutByKeyBind( - const ShortcutKeyBind& key_bind) const; - - void Install(Control* control); - void Uninstall(); - - private: - void OnKeyDown(event::KeyEventArgs& event); - - private: - std::unordered_map> map_; - - const std::vector empty_list_; - - int current_id_ = 1; - - EventRevokerListGuard event_guard_; -}; -} // namespace cru::ui diff --git a/include/cru/ui/UiEvent.hpp b/include/cru/ui/UiEvent.hpp deleted file mode 100644 index c0b2a902..00000000 --- a/include/cru/ui/UiEvent.hpp +++ /dev/null @@ -1,228 +0,0 @@ -#pragma once -#include "Base.hpp" - -#include "cru/common/Event.hpp" -#include "cru/platform/gui/Keyboard.hpp" - -#include -#include -#include -#include - -namespace cru::platform::graphics { -struct IPainter; -} - -namespace cru::ui::event { -class UiEventArgs : public Object { - public: - UiEventArgs(Object* sender, Object* original_sender) - : sender_(sender), original_sender_(original_sender), handled_(false) {} - - UiEventArgs(const UiEventArgs& other) = default; - UiEventArgs(UiEventArgs&& other) = default; - UiEventArgs& operator=(const UiEventArgs& other) = default; - UiEventArgs& operator=(UiEventArgs&& other) = default; - ~UiEventArgs() override = default; - - Object* GetSender() const { return sender_; } - - Object* GetOriginalSender() const { return original_sender_; } - - bool IsHandled() const { return handled_; } - void SetHandled(const bool handled = true) { handled_ = handled; } - - private: - Object* sender_; - Object* original_sender_; - bool handled_; -}; - -// TEventArgs must not be a reference type. This class help add reference. -// EventArgs must be reference because the IsHandled property must be settable. -template -class RoutedEvent { - public: - static_assert(std::is_base_of_v, - "TEventArgs must be subclass of UiEventArgs."); - static_assert(!std::is_reference_v, - "TEventArgs must not be reference."); - - using RawEventArgs = TEventArgs; - using IEventType = IEvent; - using EventArgs = typename IEventType::EventArgs; - - RoutedEvent() = default; - RoutedEvent(const RoutedEvent& other) = delete; - RoutedEvent(RoutedEvent&& other) = delete; - RoutedEvent& operator=(const RoutedEvent& other) = delete; - RoutedEvent& operator=(RoutedEvent&& other) = delete; - ~RoutedEvent() = default; - - IEvent* Direct() { return &direct_; } - - IEvent* Bubble() { return &bubble_; } - - IEvent* Tunnel() { return &tunnel_; } - - private: - Event direct_; - Event bubble_; - Event tunnel_; -}; - -class MouseEventArgs : public UiEventArgs { - public: - MouseEventArgs(Object* sender, Object* original_sender, - const std::optional& point = std::nullopt) - : UiEventArgs(sender, original_sender), point_(point) {} - MouseEventArgs(const MouseEventArgs& other) = default; - MouseEventArgs(MouseEventArgs&& other) = default; - MouseEventArgs& operator=(const MouseEventArgs& other) = default; - MouseEventArgs& operator=(MouseEventArgs&& other) = default; - ~MouseEventArgs() override = default; - - // This point is relative to window client lefttop. - Point GetPoint() const { return point_.value_or(Point{}); } - Point GetPointToContent(render::RenderObject* render_target) const; - - private: - std::optional point_; -}; - -class MouseButtonEventArgs : public MouseEventArgs { - public: - MouseButtonEventArgs(Object* sender, Object* original_sender, - const Point& point, const MouseButton button, - platform::gui::KeyModifier key_modifier) - : MouseEventArgs(sender, original_sender, point), - button_(button), - key_modifier_(key_modifier) {} - MouseButtonEventArgs(Object* sender, Object* original_sender, - const MouseButton button, - platform::gui::KeyModifier key_modifier) - : MouseEventArgs(sender, original_sender), - button_(button), - key_modifier_(key_modifier) {} - MouseButtonEventArgs(const MouseButtonEventArgs& other) = default; - MouseButtonEventArgs(MouseButtonEventArgs&& other) = default; - MouseButtonEventArgs& operator=(const MouseButtonEventArgs& other) = default; - MouseButtonEventArgs& operator=(MouseButtonEventArgs&& other) = default; - ~MouseButtonEventArgs() override = default; - - MouseButton GetButton() const { return button_; } - platform::gui::KeyModifier GetKeyModifier() const { return key_modifier_; } - - private: - MouseButton button_; - platform::gui::KeyModifier key_modifier_; -}; - -class MouseWheelEventArgs : public MouseEventArgs { - public: - MouseWheelEventArgs(Object* sender, Object* original_sender, - const Point& point, const float delta) - : MouseEventArgs(sender, original_sender, point), delta_(delta) {} - MouseWheelEventArgs(const MouseWheelEventArgs& other) = default; - MouseWheelEventArgs(MouseWheelEventArgs&& other) = default; - MouseWheelEventArgs& operator=(const MouseWheelEventArgs& other) = default; - MouseWheelEventArgs& operator=(MouseWheelEventArgs&& other) = default; - ~MouseWheelEventArgs() override = default; - - float GetDelta() const { return delta_; } - - private: - float delta_; -}; - -class PaintEventArgs : public UiEventArgs { - public: - PaintEventArgs(Object* sender, Object* original_sender, - platform::graphics::IPainter* painter) - : UiEventArgs(sender, original_sender), painter_(painter) {} - PaintEventArgs(const PaintEventArgs& other) = default; - PaintEventArgs(PaintEventArgs&& other) = default; - PaintEventArgs& operator=(const PaintEventArgs& other) = default; - PaintEventArgs& operator=(PaintEventArgs&& other) = default; - ~PaintEventArgs() = default; - - platform::graphics::IPainter* GetPainter() const { return painter_; } - - private: - platform::graphics::IPainter* painter_; -}; - -class FocusChangeEventArgs : public UiEventArgs { - public: - FocusChangeEventArgs(Object* sender, Object* original_sender, - const bool is_window = false) - : UiEventArgs(sender, original_sender), is_window_(is_window) {} - FocusChangeEventArgs(const FocusChangeEventArgs& other) = default; - FocusChangeEventArgs(FocusChangeEventArgs&& other) = default; - FocusChangeEventArgs& operator=(const FocusChangeEventArgs& other) = default; - FocusChangeEventArgs& operator=(FocusChangeEventArgs&& other) = default; - ~FocusChangeEventArgs() override = default; - - // Return whether the focus change is caused by the window-wide focus change. - bool IsWindow() const { return is_window_; } - - private: - bool is_window_; -}; - -/* -class ToggleEventArgs : public UiEventArgs { - public: - ToggleEventArgs(Object* sender, Object* original_sender, bool new_state) - : UiEventArgs(sender, original_sender), new_state_(new_state) {} - ToggleEventArgs(const ToggleEventArgs& other) = default; - ToggleEventArgs(ToggleEventArgs&& other) = default; - ToggleEventArgs& operator=(const ToggleEventArgs& other) = default; - ToggleEventArgs& operator=(ToggleEventArgs&& other) = default; - ~ToggleEventArgs() override = default; - - bool GetNewState() const { return new_state_; } - - private: - bool new_state_; -}; -*/ - -class KeyEventArgs : public UiEventArgs { - public: - KeyEventArgs(Object* sender, Object* original_sender, - platform::gui::KeyCode key_code, - platform::gui::KeyModifier key_modifier) - : UiEventArgs(sender, original_sender), - key_code_(key_code), - key_modifier_(key_modifier) {} - KeyEventArgs(const KeyEventArgs& other) = default; - KeyEventArgs(KeyEventArgs&& other) = default; - KeyEventArgs& operator=(const KeyEventArgs& other) = default; - KeyEventArgs& operator=(KeyEventArgs&& other) = default; - ~KeyEventArgs() override = default; - - platform::gui::KeyCode GetKeyCode() const { return key_code_; } - platform::gui::KeyModifier GetKeyModifier() const { return key_modifier_; } - - private: - platform::gui::KeyCode key_code_; - platform::gui::KeyModifier key_modifier_; -}; - -class CharEventArgs : public UiEventArgs { - public: - CharEventArgs(Object* sender, Object* original_sender, std::u16string c) - : UiEventArgs(sender, original_sender), c_(std::move(c)) {} - CharEventArgs(const CharEventArgs& other) = default; - CharEventArgs(CharEventArgs&& other) = default; - CharEventArgs& operator=(const CharEventArgs& other) = default; - CharEventArgs& operator=(CharEventArgs&& other) = default; - ~CharEventArgs() override = default; - - std::u16string GetChar() const { return c_; } - - private: - std::u16string c_; -}; -} // namespace cru::ui::event diff --git a/include/cru/ui/Window.hpp b/include/cru/ui/Window.hpp deleted file mode 100644 index 70423a14..00000000 --- a/include/cru/ui/Window.hpp +++ /dev/null @@ -1,36 +0,0 @@ -#pragma once -#include "LayoutControl.hpp" - -namespace cru::ui { -class Window final : public LayoutControl { - public: - static constexpr std::u16string_view control_type = u"Window"; - - public: - static Window* CreateOverlapped(); - - private: - Window(); - - public: - Window(const Window& other) = delete; - Window(Window&& other) = delete; - Window& operator=(const Window& other) = delete; - Window& operator=(Window&& other) = delete; - ~Window() override; - - public: - std::u16string_view GetControlType() const final; - - render::RenderObject* GetRenderObject() const override; - - protected: - void OnAddChild(Control* child, Index position) override; - void OnRemoveChild(Control* child, Index position) override; - - private: - std::unique_ptr window_host_; - - std::unique_ptr render_object_; -}; -} // namespace cru::ui diff --git a/include/cru/ui/controls/Base.hpp b/include/cru/ui/controls/Base.hpp index b550601b..82c31d1e 100644 --- a/include/cru/ui/controls/Base.hpp +++ b/include/cru/ui/controls/Base.hpp @@ -2,7 +2,7 @@ #include "../Base.hpp" namespace cru::ui::controls { -using ButtonStateStyle = BorderStyle; +using ButtonStateStyle = ui::BorderStyle; struct ButtonStyle { // corresponds to ClickState::None @@ -16,9 +16,9 @@ struct ButtonStyle { }; struct TextBoxBorderStyle { - BorderStyle normal; - BorderStyle hover; - BorderStyle focus; - BorderStyle focus_hover; + ui::BorderStyle normal; + ui::BorderStyle hover; + ui::BorderStyle focus; + ui::BorderStyle focus_hover; }; } // namespace cru::ui::controls diff --git a/include/cru/ui/controls/Button.hpp b/include/cru/ui/controls/Button.hpp index a4f727d6..e8285507 100644 --- a/include/cru/ui/controls/Button.hpp +++ b/include/cru/ui/controls/Button.hpp @@ -1,8 +1,7 @@ #pragma once -#include "../ContentControl.hpp" -#include "Base.hpp" +#include "ContentControl.hpp" -#include "../ClickDetector.hpp" +#include "../helper/ClickDetector.hpp" namespace cru::ui::controls { class Button : public ContentControl { @@ -37,6 +36,6 @@ class Button : public ContentControl { ButtonStyle style_; - ClickDetector click_detector_; + helper::ClickDetector click_detector_; }; } // namespace cru::ui::controls diff --git a/include/cru/ui/controls/Container.hpp b/include/cru/ui/controls/Container.hpp index 304d402c..d9cb8aec 100644 --- a/include/cru/ui/controls/Container.hpp +++ b/include/cru/ui/controls/Container.hpp @@ -1,5 +1,5 @@ #pragma once -#include "../ContentControl.hpp" +#include "ContentControl.hpp" namespace cru::ui::controls { class Container : public ContentControl { diff --git a/include/cru/ui/controls/ContentControl.hpp b/include/cru/ui/controls/ContentControl.hpp new file mode 100644 index 00000000..47720a87 --- /dev/null +++ b/include/cru/ui/controls/ContentControl.hpp @@ -0,0 +1,26 @@ +#pragma once +#include "Control.hpp" + +namespace cru::ui::controls { +class ContentControl : public Control { + protected: + ContentControl() = default; + + public: + ContentControl(const ContentControl& other) = delete; + ContentControl(ContentControl&& other) = delete; + ContentControl& operator=(const ContentControl& other) = delete; + ContentControl& operator=(ContentControl&& other) = delete; + ~ContentControl() override = default; + + Control* GetChild() const; + void SetChild(Control* child); + + protected: + virtual void OnChildChanged(Control* old_child, Control* new_child); + + private: + using Control::AddChild; + using Control::RemoveChild; +}; +} // namespace cru::ui::controls diff --git a/include/cru/ui/controls/Control.hpp b/include/cru/ui/controls/Control.hpp new file mode 100644 index 00000000..96aad2bd --- /dev/null +++ b/include/cru/ui/controls/Control.hpp @@ -0,0 +1,151 @@ +#pragma once +#include "Base.hpp" + +#include "../events/UiEvent.hpp" +#include "../render/Base.hpp" +#include "cru/common/Event.hpp" + +#include + +namespace cru::ui::controls { +class Control : public Object { + friend host::WindowHost; + + protected: + Control(); + + public: + Control(const Control& other) = delete; + Control(Control&& other) = delete; + Control& operator=(const Control& other) = delete; + Control& operator=(Control&& other) = delete; + ~Control() override; + + public: + virtual std::u16string_view GetControlType() const = 0; + + //*************** region: tree *************** + public: + host::WindowHost* GetWindowHost() const; + + Control* GetParent() const { return parent_; } + + const std::vector& GetChildren() const { return children_; } + + // Traverse the tree rooted the control including itself. + void TraverseDescendants(const std::function& predicate); + + public: + virtual render::RenderObject* GetRenderObject() const = 0; + + //*************** region: focus *************** + public: + bool HasFocus(); + + void SetFocus(); + + //*************** region: mouse *************** + public: + bool IsMouseOver() const { return is_mouse_over_; } + + bool CaptureMouse(); + + bool ReleaseMouse(); + + bool IsMouseCaptured(); + + //*************** region: cursor *************** + // Cursor is inherited from parent recursively if not set. + public: + // null for not set + std::shared_ptr GetCursor(); + + // will not return nullptr + std::shared_ptr GetInheritedCursor(); + + // null to unset + void SetCursor(std::shared_ptr cursor); + + //*************** region: events *************** + public: + // Raised when mouse enter the control. Even when the control itself captures + // the mouse, this event is raised as regular. But if mouse is captured by + // another control, the control will not receive any mouse enter event. You + // can use `IsMouseCaptured` to get more info. + event::RoutedEvent* MouseEnterEvent() { + return &mouse_enter_event_; + } + // Raised when mouse is leave the control. Even when the control itself + // captures the mouse, this event is raised as regular. But if mouse is + // captured by another control, the control will not receive any mouse leave + // event. You can use `IsMouseCaptured` to get more info. + event::RoutedEvent* MouseLeaveEvent() { + return &mouse_leave_event_; + } + // Raised when mouse is move in the control. + event::RoutedEvent* MouseMoveEvent() { + return &mouse_move_event_; + } + // Raised when a mouse button is pressed in the control. + event::RoutedEvent* MouseDownEvent() { + return &mouse_down_event_; + } + // Raised when a mouse button is released in the control. + event::RoutedEvent* MouseUpEvent() { + return &mouse_up_event_; + } + event::RoutedEvent* MouseWheelEvent() { + return &mouse_wheel_event_; + } + event::RoutedEvent* KeyDownEvent() { + return &key_down_event_; + } + event::RoutedEvent* KeyUpEvent() { + return &key_up_event_; + } + event::RoutedEvent* GainFocusEvent() { + return &gain_focus_event_; + } + event::RoutedEvent* LoseFocusEvent() { + return &lose_focus_event_; + } + + private: + event::RoutedEvent mouse_enter_event_; + event::RoutedEvent mouse_leave_event_; + event::RoutedEvent mouse_move_event_; + event::RoutedEvent mouse_down_event_; + event::RoutedEvent mouse_up_event_; + event::RoutedEvent mouse_wheel_event_; + + event::RoutedEvent key_down_event_; + event::RoutedEvent key_up_event_; + + event::RoutedEvent gain_focus_event_; + event::RoutedEvent lose_focus_event_; + + //*************** region: tree *************** + protected: + void AddChild(Control* control, Index position); + void RemoveChild(Index position); + virtual void OnAddChild(Control* child, Index position); + virtual void OnRemoveChild(Control* child, Index position); + virtual void OnParentChanged(Control* old_parent, Control* new_parent); + virtual void OnAttachToHost(host::WindowHost* host); + virtual void OnDetachFromHost(host::WindowHost* host); + + protected: + virtual void OnMouseHoverChange(bool newHover) { CRU_UNUSED(newHover) } + + private: + Control* parent_ = nullptr; + std::vector children_; + + host::WindowHost* window_host_ = nullptr; + + private: + bool is_mouse_over_ = false; + + std::shared_ptr cursor_ = nullptr; +}; +} // namespace cru::ui::controls diff --git a/include/cru/ui/controls/FlexLayout.hpp b/include/cru/ui/controls/FlexLayout.hpp index 0ffedba5..a6c6a40c 100644 --- a/include/cru/ui/controls/FlexLayout.hpp +++ b/include/cru/ui/controls/FlexLayout.hpp @@ -1,5 +1,5 @@ #pragma once -#include "../LayoutControl.hpp" +#include "LayoutControl.hpp" namespace cru::ui::controls { class FlexLayout : public LayoutControl { diff --git a/include/cru/ui/controls/LayoutControl.hpp b/include/cru/ui/controls/LayoutControl.hpp new file mode 100644 index 00000000..cbdb8aa2 --- /dev/null +++ b/include/cru/ui/controls/LayoutControl.hpp @@ -0,0 +1,19 @@ +#pragma once +#include "Control.hpp" + +namespace cru::ui::controls { +class LayoutControl : public Control { + protected: + LayoutControl() = default; + + public: + LayoutControl(const LayoutControl& other) = delete; + LayoutControl(LayoutControl&& other) = delete; + LayoutControl& operator=(const LayoutControl& other) = delete; + LayoutControl& operator=(LayoutControl&& other) = delete; + ~LayoutControl() override = default; + + using Control::AddChild; + using Control::RemoveChild; +}; +} // namespace cru::ui diff --git a/include/cru/ui/controls/NoChildControl.hpp b/include/cru/ui/controls/NoChildControl.hpp new file mode 100644 index 00000000..562137f1 --- /dev/null +++ b/include/cru/ui/controls/NoChildControl.hpp @@ -0,0 +1,20 @@ +#pragma once +#include "Control.hpp" + +namespace cru::ui::controls { +class NoChildControl : public Control { + protected: + NoChildControl() = default; + + public: + NoChildControl(const NoChildControl& other) = delete; + NoChildControl(NoChildControl&& other) = delete; + NoChildControl& operator=(const NoChildControl& other) = delete; + NoChildControl& operator=(NoChildControl&& other) = delete; + ~NoChildControl() override = default; + + private: + using Control::AddChild; + using Control::RemoveChild; +}; +} // namespace cru::ui diff --git a/include/cru/ui/controls/StackLayout.hpp b/include/cru/ui/controls/StackLayout.hpp index c0b95044..373b4681 100644 --- a/include/cru/ui/controls/StackLayout.hpp +++ b/include/cru/ui/controls/StackLayout.hpp @@ -1,5 +1,5 @@ #pragma once -#include "../LayoutControl.hpp" +#include "LayoutControl.hpp" namespace cru::ui::controls { class StackLayout : public LayoutControl { diff --git a/include/cru/ui/controls/TextBlock.hpp b/include/cru/ui/controls/TextBlock.hpp index 8a9a3bff..fdfdb2fa 100644 --- a/include/cru/ui/controls/TextBlock.hpp +++ b/include/cru/ui/controls/TextBlock.hpp @@ -1,5 +1,5 @@ #pragma once -#include "../NoChildControl.hpp" +#include "NoChildControl.hpp" namespace cru::ui::controls { template diff --git a/include/cru/ui/controls/TextBox.hpp b/include/cru/ui/controls/TextBox.hpp index 5976f6da..91d38c61 100644 --- a/include/cru/ui/controls/TextBox.hpp +++ b/include/cru/ui/controls/TextBox.hpp @@ -1,6 +1,5 @@ #pragma once -#include "../NoChildControl.hpp" -#include "Base.hpp" +#include "NoChildControl.hpp" #include diff --git a/include/cru/ui/controls/Window.hpp b/include/cru/ui/controls/Window.hpp new file mode 100644 index 00000000..616e2ee7 --- /dev/null +++ b/include/cru/ui/controls/Window.hpp @@ -0,0 +1,36 @@ +#pragma once +#include "LayoutControl.hpp" + +namespace cru::ui::controls { +class Window final : public LayoutControl { + public: + static constexpr std::u16string_view control_type = u"Window"; + + public: + static Window* CreateOverlapped(); + + private: + Window(); + + public: + Window(const Window& other) = delete; + Window(Window&& other) = delete; + Window& operator=(const Window& other) = delete; + Window& operator=(Window&& other) = delete; + ~Window() override; + + public: + std::u16string_view GetControlType() const final; + + render::RenderObject* GetRenderObject() const override; + + protected: + void OnAddChild(Control* child, Index position) override; + void OnRemoveChild(Control* child, Index position) override; + + private: + std::unique_ptr window_host_; + + std::unique_ptr render_object_; +}; +} // namespace cru::ui diff --git a/include/cru/ui/events/UiEvent.hpp b/include/cru/ui/events/UiEvent.hpp new file mode 100644 index 00000000..660b33f5 --- /dev/null +++ b/include/cru/ui/events/UiEvent.hpp @@ -0,0 +1,228 @@ +#pragma once +#include "../Base.hpp" + +#include "cru/common/Event.hpp" +#include "cru/platform/gui/Keyboard.hpp" + +#include +#include +#include +#include + +namespace cru::platform::graphics { +struct IPainter; +} + +namespace cru::ui::event { +class UiEventArgs : public Object { + public: + UiEventArgs(Object* sender, Object* original_sender) + : sender_(sender), original_sender_(original_sender), handled_(false) {} + + UiEventArgs(const UiEventArgs& other) = default; + UiEventArgs(UiEventArgs&& other) = default; + UiEventArgs& operator=(const UiEventArgs& other) = default; + UiEventArgs& operator=(UiEventArgs&& other) = default; + ~UiEventArgs() override = default; + + Object* GetSender() const { return sender_; } + + Object* GetOriginalSender() const { return original_sender_; } + + bool IsHandled() const { return handled_; } + void SetHandled(const bool handled = true) { handled_ = handled; } + + private: + Object* sender_; + Object* original_sender_; + bool handled_; +}; + +// TEventArgs must not be a reference type. This class help add reference. +// EventArgs must be reference because the IsHandled property must be settable. +template +class RoutedEvent { + public: + static_assert(std::is_base_of_v, + "TEventArgs must be subclass of UiEventArgs."); + static_assert(!std::is_reference_v, + "TEventArgs must not be reference."); + + using RawEventArgs = TEventArgs; + using IEventType = IEvent; + using EventArgs = typename IEventType::EventArgs; + + RoutedEvent() = default; + RoutedEvent(const RoutedEvent& other) = delete; + RoutedEvent(RoutedEvent&& other) = delete; + RoutedEvent& operator=(const RoutedEvent& other) = delete; + RoutedEvent& operator=(RoutedEvent&& other) = delete; + ~RoutedEvent() = default; + + IEvent* Direct() { return &direct_; } + + IEvent* Bubble() { return &bubble_; } + + IEvent* Tunnel() { return &tunnel_; } + + private: + Event direct_; + Event bubble_; + Event tunnel_; +}; + +class MouseEventArgs : public UiEventArgs { + public: + MouseEventArgs(Object* sender, Object* original_sender, + const std::optional& point = std::nullopt) + : UiEventArgs(sender, original_sender), point_(point) {} + MouseEventArgs(const MouseEventArgs& other) = default; + MouseEventArgs(MouseEventArgs&& other) = default; + MouseEventArgs& operator=(const MouseEventArgs& other) = default; + MouseEventArgs& operator=(MouseEventArgs&& other) = default; + ~MouseEventArgs() override = default; + + // This point is relative to window client lefttop. + Point GetPoint() const { return point_.value_or(Point{}); } + Point GetPointToContent(render::RenderObject* render_target) const; + + private: + std::optional point_; +}; + +class MouseButtonEventArgs : public MouseEventArgs { + public: + MouseButtonEventArgs(Object* sender, Object* original_sender, + const Point& point, const MouseButton button, + platform::gui::KeyModifier key_modifier) + : MouseEventArgs(sender, original_sender, point), + button_(button), + key_modifier_(key_modifier) {} + MouseButtonEventArgs(Object* sender, Object* original_sender, + const MouseButton button, + platform::gui::KeyModifier key_modifier) + : MouseEventArgs(sender, original_sender), + button_(button), + key_modifier_(key_modifier) {} + MouseButtonEventArgs(const MouseButtonEventArgs& other) = default; + MouseButtonEventArgs(MouseButtonEventArgs&& other) = default; + MouseButtonEventArgs& operator=(const MouseButtonEventArgs& other) = default; + MouseButtonEventArgs& operator=(MouseButtonEventArgs&& other) = default; + ~MouseButtonEventArgs() override = default; + + MouseButton GetButton() const { return button_; } + platform::gui::KeyModifier GetKeyModifier() const { return key_modifier_; } + + private: + MouseButton button_; + platform::gui::KeyModifier key_modifier_; +}; + +class MouseWheelEventArgs : public MouseEventArgs { + public: + MouseWheelEventArgs(Object* sender, Object* original_sender, + const Point& point, const float delta) + : MouseEventArgs(sender, original_sender, point), delta_(delta) {} + MouseWheelEventArgs(const MouseWheelEventArgs& other) = default; + MouseWheelEventArgs(MouseWheelEventArgs&& other) = default; + MouseWheelEventArgs& operator=(const MouseWheelEventArgs& other) = default; + MouseWheelEventArgs& operator=(MouseWheelEventArgs&& other) = default; + ~MouseWheelEventArgs() override = default; + + float GetDelta() const { return delta_; } + + private: + float delta_; +}; + +class PaintEventArgs : public UiEventArgs { + public: + PaintEventArgs(Object* sender, Object* original_sender, + platform::graphics::IPainter* painter) + : UiEventArgs(sender, original_sender), painter_(painter) {} + PaintEventArgs(const PaintEventArgs& other) = default; + PaintEventArgs(PaintEventArgs&& other) = default; + PaintEventArgs& operator=(const PaintEventArgs& other) = default; + PaintEventArgs& operator=(PaintEventArgs&& other) = default; + ~PaintEventArgs() = default; + + platform::graphics::IPainter* GetPainter() const { return painter_; } + + private: + platform::graphics::IPainter* painter_; +}; + +class FocusChangeEventArgs : public UiEventArgs { + public: + FocusChangeEventArgs(Object* sender, Object* original_sender, + const bool is_window = false) + : UiEventArgs(sender, original_sender), is_window_(is_window) {} + FocusChangeEventArgs(const FocusChangeEventArgs& other) = default; + FocusChangeEventArgs(FocusChangeEventArgs&& other) = default; + FocusChangeEventArgs& operator=(const FocusChangeEventArgs& other) = default; + FocusChangeEventArgs& operator=(FocusChangeEventArgs&& other) = default; + ~FocusChangeEventArgs() override = default; + + // Return whether the focus change is caused by the window-wide focus change. + bool IsWindow() const { return is_window_; } + + private: + bool is_window_; +}; + +/* +class ToggleEventArgs : public UiEventArgs { + public: + ToggleEventArgs(Object* sender, Object* original_sender, bool new_state) + : UiEventArgs(sender, original_sender), new_state_(new_state) {} + ToggleEventArgs(const ToggleEventArgs& other) = default; + ToggleEventArgs(ToggleEventArgs&& other) = default; + ToggleEventArgs& operator=(const ToggleEventArgs& other) = default; + ToggleEventArgs& operator=(ToggleEventArgs&& other) = default; + ~ToggleEventArgs() override = default; + + bool GetNewState() const { return new_state_; } + + private: + bool new_state_; +}; +*/ + +class KeyEventArgs : public UiEventArgs { + public: + KeyEventArgs(Object* sender, Object* original_sender, + platform::gui::KeyCode key_code, + platform::gui::KeyModifier key_modifier) + : UiEventArgs(sender, original_sender), + key_code_(key_code), + key_modifier_(key_modifier) {} + KeyEventArgs(const KeyEventArgs& other) = default; + KeyEventArgs(KeyEventArgs&& other) = default; + KeyEventArgs& operator=(const KeyEventArgs& other) = default; + KeyEventArgs& operator=(KeyEventArgs&& other) = default; + ~KeyEventArgs() override = default; + + platform::gui::KeyCode GetKeyCode() const { return key_code_; } + platform::gui::KeyModifier GetKeyModifier() const { return key_modifier_; } + + private: + platform::gui::KeyCode key_code_; + platform::gui::KeyModifier key_modifier_; +}; + +class CharEventArgs : public UiEventArgs { + public: + CharEventArgs(Object* sender, Object* original_sender, std::u16string c) + : UiEventArgs(sender, original_sender), c_(std::move(c)) {} + CharEventArgs(const CharEventArgs& other) = default; + CharEventArgs(CharEventArgs&& other) = default; + CharEventArgs& operator=(const CharEventArgs& other) = default; + CharEventArgs& operator=(CharEventArgs&& other) = default; + ~CharEventArgs() override = default; + + std::u16string GetChar() const { return c_; } + + private: + std::u16string c_; +}; +} // namespace cru::ui::event diff --git a/include/cru/ui/helper/ClickDetector.hpp b/include/cru/ui/helper/ClickDetector.hpp new file mode 100644 index 00000000..0df77c60 --- /dev/null +++ b/include/cru/ui/helper/ClickDetector.hpp @@ -0,0 +1,87 @@ +#pragma once +#include "../controls/Control.hpp" + +namespace cru::ui::helper { +class ClickEventArgs : Object { + public: + ClickEventArgs(controls::Control* sender, const Point& down_point, + const Point& up_point, MouseButton button) + : sender_(sender), + down_point_(down_point), + up_point_(up_point), + button_(button) {} + + CRU_DEFAULT_COPY(ClickEventArgs) + CRU_DEFAULT_MOVE(ClickEventArgs) + + ~ClickEventArgs() override = default; + + controls::Control* GetSender() const { return sender_; } + Point GetDownPoint() const { return down_point_; } + Point GetUpPoint() const { return up_point_; } + MouseButton GetButton() const { return button_; } + + private: + controls::Control* sender_; + Point down_point_; + Point up_point_; + MouseButton button_; +}; + +enum class ClickState { + None, // Mouse is outside the control. + Hover, // Mouse hovers on the control but not pressed + Press, // Mouse is pressed and if released click is done. + PressInactive // Mouse is pressed but if released click is canceled. +}; + +class ClickDetector : public Object { + CRU_DEFINE_CLASS_LOG_TAG(u"cru::ui::ClickDetector") + + public: + explicit ClickDetector(controls::Control* control); + + CRU_DELETE_COPY(ClickDetector) + CRU_DELETE_MOVE(ClickDetector) + + ~ClickDetector() override = default; + + controls::Control* GetControl() const { return control_; } + + ClickState GetState() const { return state_; } + + // Default is enable. + bool IsEnabled() const { return enable_; } + // If disable when user is pressing, the pressing is deactivated. + void SetEnabled(bool enable); + + // Default is left and right. + MouseButton GetTriggerButton() const { return trigger_button_; } + // If unset the trigger button when user is pressing, the pressing is + // deactivated. + void SetTriggerButton(MouseButton trigger_button); + + IEvent* ClickEvent() { return &event_; } + + IEvent* StateChangeEvent() { return &state_change_event_; } + + private: + void SetState(ClickState state); + + private: + controls::Control* control_; + + ClickState state_; + + bool enable_ = true; + MouseButton trigger_button_ = mouse_buttons::left | mouse_buttons::right; + + Event event_; + Event state_change_event_; + + std::vector event_rovoker_guards_; + + Point down_point_; + MouseButton button_; +}; +} // namespace cru::ui::helper diff --git a/include/cru/ui/helper/ShortcutHub.hpp b/include/cru/ui/helper/ShortcutHub.hpp new file mode 100644 index 00000000..a4ff2da2 --- /dev/null +++ b/include/cru/ui/helper/ShortcutHub.hpp @@ -0,0 +1,129 @@ +#pragma once +#include "../Base.hpp" + +#include "../events/UiEvent.hpp" +#include "cru/common/Event.hpp" +#include "cru/platform/gui/Keyboard.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace cru::ui::helper { + +class ShortcutKeyBind { + public: + ShortcutKeyBind(platform::gui::KeyCode key, + platform::gui::KeyModifier modifier) + : key_(key), modifier_(modifier) {} + + CRU_DEFAULT_COPY(ShortcutKeyBind) + CRU_DEFAULT_MOVE(ShortcutKeyBind) + + ~ShortcutKeyBind() = default; + + platform::gui::KeyCode GetKey() const { return key_; } + platform::gui::KeyModifier GetModifier() const { return modifier_; } + + bool Is(platform::gui::KeyCode key, + platform::gui::KeyModifier modifier) const { + return key == key_ && modifier == modifier_; + } + + bool operator==(const ShortcutKeyBind& other) const { + return this->key_ == other.key_ && this->modifier_ == other.modifier_; + } + + bool operator!=(const ShortcutKeyBind& other) const { + return !this->operator==(other); + } + + std::u16string ToString() { + std::u16string result = u"("; + result += platform::gui::ToString(modifier_); + result += u")"; + result += platform::gui::ToString(key_); + return result; + } + + private: + platform::gui::KeyCode key_; + platform::gui::KeyModifier modifier_; +}; +} // namespace cru::ui::helper + +namespace std { +template <> +struct hash { + std::size_t operator()(const cru::ui::helper::ShortcutKeyBind& value) const { + std::size_t result = 0; + cru::hash_combine(result, static_cast(value.GetKey())); + cru::hash_combine(result, static_cast(value.GetModifier())); + return result; + } +}; +} // namespace std + +namespace cru::ui::helper { +struct Shortcut { + // Just for debug. + std::u16string name; + ShortcutKeyBind key_bind; + // Return true if it consumes the shortcut. Or return false if it does not + // handle the shortcut. + std::function handler; +}; + +struct ShortcutInfo { + int id; + std::u16string name; + ShortcutKeyBind key_bind; + std::function handler; +}; + +class ShortcutHub : public Object { + public: + ShortcutHub() = default; + + CRU_DELETE_COPY(ShortcutHub) + CRU_DELETE_MOVE(ShortcutHub) + + ~ShortcutHub() override = default; + + int RegisterShortcut(std::u16string name, ShortcutKeyBind bind, + std::function handler) { + return RegisterShortcut({std::move(name), bind, std::move(handler)}); + } + + // Return an id used for unregistering. + int RegisterShortcut(Shortcut shortcut); + + void UnregisterShortcut(int id); + + std::vector GetAllShortcuts() const; + std::optional GetShortcut(int id) const; + const std::vector& GetShortcutByKeyBind( + const ShortcutKeyBind& key_bind) const; + + void Install(controls::Control* control); + void Uninstall(); + + private: + void OnKeyDown(event::KeyEventArgs& event); + + private: + std::unordered_map> map_; + + const std::vector empty_list_; + + int current_id_ = 1; + + EventRevokerListGuard event_guard_; +}; +} // namespace cru::ui::helper diff --git a/include/cru/ui/host/WindowHost.hpp b/include/cru/ui/host/WindowHost.hpp index 81eabb52..56f37382 100644 --- a/include/cru/ui/host/WindowHost.hpp +++ b/include/cru/ui/host/WindowHost.hpp @@ -1,10 +1,10 @@ #pragma once #include "../Base.hpp" +#include "../render/Base.hpp" #include "cru/common/Event.hpp" #include "cru/platform/gui/UiApplication.hpp" #include "cru/platform/gui/Window.hpp" -#include "../render/Base.hpp" #include #include @@ -19,7 +19,7 @@ class WindowHost : public Object { CRU_DEFINE_CLASS_LOG_TAG(u"cru::ui::host::WindowHost") public: - WindowHost(Control* root_control); + WindowHost(controls::Control* root_control); CRU_DELETE_COPY(WindowHost) CRU_DELETE_MOVE(WindowHost) @@ -61,13 +61,15 @@ class WindowHost : public Object { // control. Even when mouse is captured by another control, this function // return the control under cursor. You can use `GetMouseCaptureControl` to // get more info. - Control* GetMouseHoverControl() const { return mouse_hover_control_; } + controls::Control* GetMouseHoverControl() const { + return mouse_hover_control_; + } //*************** region: focus *************** - Control* GetFocusControl(); + controls::Control* GetFocusControl(); - void SetFocusControl(Control* control); + void SetFocusControl(controls::Control* control); //*************** region: focus *************** @@ -81,12 +83,12 @@ class WindowHost : public Object { // and capture is released, mouse enter event will be sent to the mouse-hover // control. If mouse is not on the capturing control and capture is set, mouse // leave event will be sent to the mouse-hover control. - bool CaptureMouseFor(Control* control); + bool CaptureMouseFor(controls::Control* control); // Return null if not captured. - Control* GetMouseCaptureControl(); + controls::Control* GetMouseCaptureControl(); - Control* HitTest(const Point& point); + controls::Control* HitTest(const Point& point); void UpdateCursor(); @@ -94,23 +96,19 @@ class WindowHost : public Object { //*************** region: native messages *************** void OnNativeDestroy(platform::gui::INativeWindow* window, std::nullptr_t); void OnNativePaint(platform::gui::INativeWindow* window, std::nullptr_t); - void OnNativeResize(platform::gui::INativeWindow* window, - const Size& size); + void OnNativeResize(platform::gui::INativeWindow* window, const Size& size); void OnNativeFocus(platform::gui::INativeWindow* window, cru::platform::gui::FocusChangeType focus); - void OnNativeMouseEnterLeave( - platform::gui::INativeWindow* window, - cru::platform::gui::MouseEnterLeaveType enter); + void OnNativeMouseEnterLeave(platform::gui::INativeWindow* window, + cru::platform::gui::MouseEnterLeaveType enter); void OnNativeMouseMove(platform::gui::INativeWindow* window, const Point& point); - void OnNativeMouseDown( - platform::gui::INativeWindow* window, - const platform::gui::NativeMouseButtonEventArgs& args); - void OnNativeMouseUp( - platform::gui::INativeWindow* window, - const platform::gui::NativeMouseButtonEventArgs& args); + void OnNativeMouseDown(platform::gui::INativeWindow* window, + const platform::gui::NativeMouseButtonEventArgs& args); + void OnNativeMouseUp(platform::gui::INativeWindow* window, + const platform::gui::NativeMouseButtonEventArgs& args); void OnNativeKeyDown(platform::gui::INativeWindow* window, const platform::gui::NativeKeyEventArgs& args); @@ -119,13 +117,13 @@ class WindowHost : public Object { //*************** region: event dispatcher helper *************** - void DispatchMouseHoverControlChangeEvent(Control* old_control, - Control* new_control, + void DispatchMouseHoverControlChangeEvent(controls::Control* old_control, + controls::Control* new_control, const Point& point, bool no_leave, bool no_enter); private: - Control* root_control_ = nullptr; + controls::Control* root_control_ = nullptr; render::RenderObject* root_render_object_ = nullptr; platform::gui::INativeWindow* native_window_ = nullptr; @@ -137,12 +135,12 @@ class WindowHost : public Object { std::vector event_revoker_guards_; - Control* mouse_hover_control_ = nullptr; + controls::Control* mouse_hover_control_ = nullptr; - Control* focus_control_; + controls::Control* focus_control_; - Control* mouse_captured_control_ = nullptr; + controls::Control* mouse_captured_control_ = nullptr; bool layout_prefer_to_fill_window_ = true; }; -} // namespace cru::ui +} // namespace cru::ui::host diff --git a/include/cru/ui/render/RenderObject.hpp b/include/cru/ui/render/RenderObject.hpp index 635a541e..2b166efc 100644 --- a/include/cru/ui/render/RenderObject.hpp +++ b/include/cru/ui/render/RenderObject.hpp @@ -62,8 +62,10 @@ class RenderObject : public Object { RenderObject& operator=(RenderObject&& other) = delete; ~RenderObject() override = default; - Control* GetAttachedControl() const { return control_; } - void SetAttachedControl(Control* new_control) { control_ = new_control; } + controls::Control* GetAttachedControl() const { return control_; } + void SetAttachedControl(controls::Control* new_control) { + control_ = new_control; + } host::WindowHost* GetWindowHost() const { return window_host_; } @@ -135,7 +137,9 @@ class RenderObject : public Object { // Add offset before pass point to children. virtual RenderObject* HitTest(const Point& point) = 0; - IEvent* AttachToHostEvent() { return &attach_to_host_event_; } + IEvent* AttachToHostEvent() { + return &attach_to_host_event_; + } IEvent* DetachFromHostEvent() { return &detach_from_host_event_; } @@ -208,7 +212,7 @@ class RenderObject : public Object { void SetWindowHostRecursive(host::WindowHost* host); private: - Control* control_ = nullptr; + controls::Control* control_ = nullptr; host::WindowHost* window_host_ = nullptr; RenderObject* parent_ = nullptr; diff --git a/include/cru/win/gui/UiApplication.hpp b/include/cru/win/gui/UiApplication.hpp index 0f733cd4..4cf46858 100644 --- a/include/cru/win/gui/UiApplication.hpp +++ b/include/cru/win/gui/UiApplication.hpp @@ -41,7 +41,7 @@ class WinUiApplication : public WinNativeResource, void CancelTimer(long long id) override; std::vector GetAllWindow() override; - INativeWindow* CreateWindow(INativeWindow* parent) override; + INativeWindow* CreateWindow(INativeWindow* parent, CreateWindowFlag flag) override; cru::platform::graphics::IGraphFactory* GetGraphFactory() override; diff --git a/src/ui/CMakeLists.txt b/src/ui/CMakeLists.txt index 449fb4d9..2f0eb10d 100644 --- a/src/ui/CMakeLists.txt +++ b/src/ui/CMakeLists.txt @@ -4,23 +4,23 @@ add_library(cru_ui STATIC Helper.hpp host/RoutedEventDispatch.hpp - ClickDetector.cpp - ContentControl.cpp - Control.cpp Helper.cpp - LayoutControl.cpp - NoChildControl.cpp - ShortcutHub.cpp - UiEvent.cpp UiManager.cpp - Window.cpp controls/Button.cpp controls/Container.cpp + controls/ContentControl.cpp + controls/Control.cpp controls/FlexLayout.cpp + controls/LayoutControl.cpp + controls/NoChildControl.cpp controls/StackLayout.cpp controls/TextBlock.cpp controls/TextBox.cpp controls/TextControlService.hpp + controls/Window.cpp + events/UiEvent.cpp + helper/ClickDetector.cpp + helper/ShortcutHub.cpp host/LayoutPaintCycler.cpp host/WindowHost.cpp render/BorderRenderObject.cpp @@ -34,23 +34,23 @@ add_library(cru_ui STATIC ) target_sources(cru_ui PUBLIC ${CRU_UI_INCLUDE_DIR}/Base.hpp - ${CRU_UI_INCLUDE_DIR}/ClickDetector.hpp - ${CRU_UI_INCLUDE_DIR}/ContentControl.hpp - ${CRU_UI_INCLUDE_DIR}/Control.hpp ${CRU_UI_INCLUDE_DIR}/DebugFlags.hpp - ${CRU_UI_INCLUDE_DIR}/LayoutControl.hpp - ${CRU_UI_INCLUDE_DIR}/NoChildControl.hpp - ${CRU_UI_INCLUDE_DIR}/ShortcutHub.hpp - ${CRU_UI_INCLUDE_DIR}/UiEvent.hpp ${CRU_UI_INCLUDE_DIR}/UiManager.hpp - ${CRU_UI_INCLUDE_DIR}/Window.hpp ${CRU_UI_INCLUDE_DIR}/controls/Base.hpp ${CRU_UI_INCLUDE_DIR}/controls/Button.hpp ${CRU_UI_INCLUDE_DIR}/controls/Container.hpp + ${CRU_UI_INCLUDE_DIR}/controls/ContentControl.hpp + ${CRU_UI_INCLUDE_DIR}/controls/Control.hpp ${CRU_UI_INCLUDE_DIR}/controls/FlexLayout.hpp + ${CRU_UI_INCLUDE_DIR}/controls/LayoutControl.hpp + ${CRU_UI_INCLUDE_DIR}/controls/NoChildControl.hpp ${CRU_UI_INCLUDE_DIR}/controls/StackLayout.hpp ${CRU_UI_INCLUDE_DIR}/controls/TextBox.hpp ${CRU_UI_INCLUDE_DIR}/controls/TextBlock.hpp + ${CRU_UI_INCLUDE_DIR}/controls/Window.hpp + ${CRU_UI_INCLUDE_DIR}/events/UiEvent.hpp + ${CRU_UI_INCLUDE_DIR}/helper/ClickDetector.hpp + ${CRU_UI_INCLUDE_DIR}/helper/ShortcutHub.hpp ${CRU_UI_INCLUDE_DIR}/host/LayoutPaintCycler.hpp ${CRU_UI_INCLUDE_DIR}/host/WindowHost.hpp ${CRU_UI_INCLUDE_DIR}/render/Base.hpp diff --git a/src/ui/ClickDetector.cpp b/src/ui/ClickDetector.cpp deleted file mode 100644 index 09f208cd..00000000 --- a/src/ui/ClickDetector.cpp +++ /dev/null @@ -1,131 +0,0 @@ -#include "cru/ui/ClickDetector.hpp" - -#include "cru/common/Logger.hpp" - -#include - -namespace cru::ui { -ClickDetector::ClickDetector(Control* control) { - Expects(control); - control_ = control; - - event_rovoker_guards_.push_back( - EventRevokerGuard(control->MouseEnterEvent()->Direct()->AddHandler( - [this](event::MouseEventArgs&) { - if (this->enable_) { - if (this->state_ == ClickState::PressInactive) { - if ((this->button_ & this->trigger_button_)) { - this->SetState(ClickState::Press); - } - } else { - this->SetState(ClickState::Hover); - } - } - }))); - - event_rovoker_guards_.push_back( - EventRevokerGuard(control->MouseLeaveEvent()->Direct()->AddHandler( - [this](event::MouseEventArgs&) { - if (this->enable_) { - if (this->state_ == ClickState::Press) { - if ((this->button_ & this->trigger_button_)) { - this->SetState(ClickState::PressInactive); - } - } else { - this->SetState(ClickState::None); - } - } - }))); - - event_rovoker_guards_.push_back( - EventRevokerGuard(control->MouseDownEvent()->Direct()->AddHandler( - [this](event::MouseButtonEventArgs& args) { - const auto button = args.GetButton(); - if (this->enable_ && (button & this->trigger_button_) && - this->state_ == ClickState::Hover) { - if (!this->control_->CaptureMouse()) { - log::TagDebug(log_tag, - u"Failed to capture mouse when begin click."); - return; - } - this->down_point_ = args.GetPoint(); - this->button_ = button; - this->SetState(ClickState::Press); - } - }))); - - event_rovoker_guards_.push_back( - EventRevokerGuard(control->MouseUpEvent()->Direct()->AddHandler( - [this](event::MouseButtonEventArgs& args) { - const auto button = args.GetButton(); - if (this->enable_ && (button & this->trigger_button_) && - button == button_) { - if (this->state_ == ClickState::Press) { - this->SetState(ClickState::Hover); - this->event_.Raise(ClickEventArgs{this->control_, - this->down_point_, - args.GetPoint(), button}); - this->control_->ReleaseMouse(); - } else if (this->state_ == ClickState::PressInactive) { - this->SetState(ClickState::None); - this->control_->ReleaseMouse(); - } - } - }))); -} // namespace cru::ui - -void ClickDetector::SetEnabled(bool enable) { - if (enable == enable_) { - return; - } - - enable_ = enable; - if (enable) { - SetState(control_->IsMouseOver() ? ClickState::Hover : ClickState::None); - } else { - if (state_ == ClickState::Press || state_ == ClickState::PressInactive) { - SetState(ClickState::None); - control_->ReleaseMouse(); - } else if (state_ == ClickState::Hover) { - SetState(ClickState::None); - } - } -} - -void ClickDetector::SetTriggerButton(MouseButton trigger_button) { - if (trigger_button == trigger_button_) { - return; - } - - trigger_button_ = trigger_button; - if ((state_ == ClickState::Press || state_ == ClickState::PressInactive) && - !(button_ & trigger_button)) { - SetState(control_->IsMouseOver() ? ClickState::Hover : ClickState::None); - control_->ReleaseMouse(); - } -} - -void ClickDetector::SetState(ClickState state) { -#ifdef CRU_DEBUG - auto to_string = [](ClickState state) -> std::u16string_view { - switch (state) { - case ClickState::None: - return u"None"; - case ClickState::Hover: - return u"Hover"; - case ClickState::Press: - return u"Press"; - case ClickState::PressInactive: - return u"PressInvactive"; - default: - UnreachableCode(); - } - }; - log::TagDebug(log_tag, u"Click state changed, new state: {}.", - to_string(state)); -#endif - - state_ = state; - state_change_event_.Raise(state); -} -} // namespace cru::ui diff --git a/src/ui/ContentControl.cpp b/src/ui/ContentControl.cpp deleted file mode 100644 index 19b1b06f..00000000 --- a/src/ui/ContentControl.cpp +++ /dev/null @@ -1,27 +0,0 @@ -#include "cru/ui/ContentControl.hpp" - -#include "cru/ui/Window.hpp" - -namespace cru::ui { -Control* ContentControl::GetChild() const { - if (GetChildren().empty()) return nullptr; - return GetChildren()[0]; -} - -void ContentControl::SetChild(Control* child) { - Control* old_child = nullptr; - if (!GetChildren().empty()) { - old_child = GetChildren()[0]; - this->RemoveChild(0); - } - if (child) { - this->AddChild(child, 0); - } - OnChildChanged(old_child, child); -} - -void ContentControl::OnChildChanged(Control* old_child, Control* new_child) { - CRU_UNUSED(old_child) - CRU_UNUSED(new_child) -} -} // namespace cru::ui diff --git a/src/ui/Control.cpp b/src/ui/Control.cpp deleted file mode 100644 index 23a3cef2..00000000 --- a/src/ui/Control.cpp +++ /dev/null @@ -1,157 +0,0 @@ -#include "cru/ui/Control.hpp" - -#include "cru/common/Base.hpp" -#include "cru/platform/gui/Cursor.hpp" -#include "cru/platform/gui/UiApplication.hpp" -#include "cru/ui/Base.hpp" -#include "cru/ui/host/WindowHost.hpp" -#include "cru/ui/render/RenderObject.hpp" - -#include - -namespace cru::ui { -using platform::gui::ICursor; -using platform::gui::IUiApplication; -using platform::gui::SystemCursorType; - -Control::Control() { - MouseEnterEvent()->Direct()->AddHandler([this](event::MouseEventArgs&) { - this->is_mouse_over_ = true; - this->OnMouseHoverChange(true); - }); - - MouseLeaveEvent()->Direct()->AddHandler([this](event::MouseEventArgs&) { - this->is_mouse_over_ = false; - this->OnMouseHoverChange(true); - }); -} - -Control::~Control() { - for (const auto child : children_) delete child; -} - -host::WindowHost* Control::GetWindowHost() const { return window_host_; } - -void Control::TraverseDescendants( - const std::function& predicate) { - predicate(this); - for (auto c : GetChildren()) c->TraverseDescendants(predicate); -} - -bool Control::HasFocus() { - auto host = GetWindowHost(); - if (host == nullptr) return false; - - return host->GetFocusControl() == this; -} - -bool Control::CaptureMouse() { - auto host = GetWindowHost(); - if (host == nullptr) return false; - - return host->CaptureMouseFor(this); -} - -void Control::SetFocus() { - auto host = GetWindowHost(); - if (host == nullptr) return; - - host->SetFocusControl(this); -} - -bool Control::ReleaseMouse() { - auto host = GetWindowHost(); - if (host == nullptr) return false; - - return host->CaptureMouseFor(nullptr); -} - -bool Control::IsMouseCaptured() { - auto host = GetWindowHost(); - if (host == nullptr) return false; - - return host->GetMouseCaptureControl() == this; -} - -std::shared_ptr Control::GetCursor() { return cursor_; } - -std::shared_ptr Control::GetInheritedCursor() { - Control* control = this; - while (control != nullptr) { - const auto cursor = control->GetCursor(); - if (cursor != nullptr) return cursor; - control = control->GetParent(); - } - return IUiApplication::GetInstance()->GetCursorManager()->GetSystemCursor( - SystemCursorType::Arrow); -} - -void Control::SetCursor(std::shared_ptr cursor) { - cursor_ = std::move(cursor); - const auto host = GetWindowHost(); - if (host != nullptr) { - host->UpdateCursor(); - } -} - -void Control::AddChild(Control* control, const Index position) { - Expects(control->GetParent() == - nullptr); // The control already has a parent. - Expects(position >= 0); - Expects(position <= static_cast( - children_.size())); // The position is out of range. - - children_.insert(children_.cbegin() + position, control); - - const auto old_parent = control->parent_; - control->parent_ = this; - - OnAddChild(control, position); - control->OnParentChanged(old_parent, this); - - if (window_host_) - control->TraverseDescendants([this](Control* control) { - control->window_host_ = window_host_; - control->OnAttachToHost(window_host_); - }); -} - -void Control::RemoveChild(const Index position) { - Expects(position >= 0); - Expects(position < static_cast( - children_.size())); // The position is out of range. - - const auto i = children_.cbegin() + position; - const auto control = *i; - - children_.erase(i); - control->parent_ = nullptr; - - OnRemoveChild(control, position); - control->OnParentChanged(this, nullptr); - - if (window_host_) - control->TraverseDescendants([this](Control* control) { - control->window_host_ = nullptr; - control->OnDetachFromHost(window_host_); - }); -} - -void Control::OnAddChild(Control* child, Index position) { - CRU_UNUSED(child) - CRU_UNUSED(position) -} -void Control::OnRemoveChild(Control* child, Index position) { - CRU_UNUSED(child) - CRU_UNUSED(position) -} - -void Control::OnParentChanged(Control* old_parent, Control* new_parent) { - CRU_UNUSED(old_parent) - CRU_UNUSED(new_parent) -} - -void Control::OnAttachToHost(host::WindowHost* host) { CRU_UNUSED(host) } - -void Control::OnDetachFromHost(host::WindowHost* host) { CRU_UNUSED(host) } -} // namespace cru::ui diff --git a/src/ui/LayoutControl.cpp b/src/ui/LayoutControl.cpp deleted file mode 100644 index 351026f9..00000000 --- a/src/ui/LayoutControl.cpp +++ /dev/null @@ -1,6 +0,0 @@ -#include "cru/ui/LayoutControl.hpp" - -#include "cru/ui/Window.hpp" - -namespace cru::ui { -} // namespace cru::ui diff --git a/src/ui/NoChildControl.cpp b/src/ui/NoChildControl.cpp deleted file mode 100644 index 8adbe3bc..00000000 --- a/src/ui/NoChildControl.cpp +++ /dev/null @@ -1,3 +0,0 @@ -#include "cru/ui/NoChildControl.hpp" - -namespace cru::ui {} diff --git a/src/ui/ShortcutHub.cpp b/src/ui/ShortcutHub.cpp deleted file mode 100644 index c9ce6cdd..00000000 --- a/src/ui/ShortcutHub.cpp +++ /dev/null @@ -1,120 +0,0 @@ -#include "cru/ui/ShortcutHub.hpp" - -#include "cru/common/Logger.hpp" -#include "cru/ui/Control.hpp" -#include "cru/ui/DebugFlags.hpp" - -#include -#include -#include -#include - -namespace cru::ui { -int ShortcutHub::RegisterShortcut(Shortcut shortcut) { - const int id = current_id_++; - map_[shortcut.key_bind].push_back({id, std::move(shortcut.name), - shortcut.key_bind, - std::move(shortcut.handler)}); - return id; -} - -void ShortcutHub::UnregisterShortcut(int id) { - if (id <= 0) return; - for (auto& pair : map_) { - auto& list = pair.second; - auto result = - std::find_if(list.cbegin(), list.cend(), - [id](const ShortcutInfo& info) { return info.id == id; }); - if (result != list.cend()) { - list.erase(result); - } - } -} - -std::vector ShortcutHub::GetAllShortcuts() const { - std::vector result; - - for (const auto& pair : map_) { - std::copy(pair.second.cbegin(), pair.second.cend(), - std::back_inserter(result)); - } - - return result; -} - -std::optional ShortcutHub::GetShortcut(int id) const { - for (auto& pair : map_) { - auto& list = pair.second; - auto result = - std::find_if(list.cbegin(), list.cend(), - [id](const ShortcutInfo& info) { return info.id == id; }); - if (result != list.cend()) { - return *result; - } - } - return std::nullopt; -} - -const std::vector& ShortcutHub::GetShortcutByKeyBind( - const ShortcutKeyBind& key_bind) const { - auto result = map_.find(key_bind); - if (result != map_.cend()) return result->second; - return empty_list_; -} - -void ShortcutHub::Install(Control* control) { - if (!event_guard_.IsEmpty()) { - log::Error(u"Shortcut hub is already installed. Failed to install."); - return; - } - - event_guard_ += control->KeyDownEvent()->Bubble()->AddHandler( - std::bind(&ShortcutHub::OnKeyDown, this, std::placeholders::_1)); -} - -void ShortcutHub::Uninstall() { - if (event_guard_.IsEmpty()) { - log::Warn(u"Shortcut hub is not installed. Failed to uninstall."); - return; - } - - event_guard_.Clear(); -} - -void ShortcutHub::OnKeyDown(event::KeyEventArgs& event) { - ShortcutKeyBind key_bind(event.GetKeyCode(), event.GetKeyModifier()); - const auto& shortcut_list = this->GetShortcutByKeyBind(key_bind); - - if constexpr (debug_flags::shortcut) { - if (shortcut_list.empty()) { - log::Debug(u"No shortcut for key bind {}.", key_bind.ToString()); - } - log::Debug(u"Begin to handle shortcut for key bind {}.", - key_bind.ToString()); - } - - for (const auto& shortcut : shortcut_list) { - auto is_handled = shortcut.handler(); - if (is_handled) { - if constexpr (debug_flags::shortcut) { - log::Debug(u"Handle {} handled it.", shortcut.name); - } - - event.SetHandled(); - - break; - } else { - if constexpr (debug_flags::shortcut) { - log::Debug(u"Handle {} disdn't handle it.", shortcut.name); - } - } - } - - if constexpr (debug_flags::shortcut) { - if (!shortcut_list.empty()) { - log::Debug(u"End handling shortcut for key bind {}.", - key_bind.ToString()); - } - } -} -} // namespace cru::ui diff --git a/src/ui/UiEvent.cpp b/src/ui/UiEvent.cpp deleted file mode 100644 index 74dd54dc..00000000 --- a/src/ui/UiEvent.cpp +++ /dev/null @@ -1,10 +0,0 @@ -#include "cru/ui/UiEvent.hpp" - -#include "cru/ui/render/RenderObject.hpp" - -namespace cru::ui::event { -Point MouseEventArgs::GetPointToContent( - render::RenderObject* render_object) const { - return render_object->FromRootToContent(GetPoint()); -} -} // namespace cru::ui::event diff --git a/src/ui/Window.cpp b/src/ui/Window.cpp deleted file mode 100644 index c49140a4..00000000 --- a/src/ui/Window.cpp +++ /dev/null @@ -1,32 +0,0 @@ -#include "cru/ui/Window.hpp" - -#include "cru/common/Base.hpp" -#include "cru/ui/host/WindowHost.hpp" -#include "cru/ui/render/Base.hpp" -#include "cru/ui/render/StackLayoutRenderObject.hpp" - -namespace cru::ui { -Window* Window::CreateOverlapped() { return new Window(); } - -Window::Window() : render_object_(new render::StackLayoutRenderObject()) { - render_object_->SetAttachedControl(this); - window_host_ = std::make_unique(this); -} - -Window::~Window() {} - -std::u16string_view Window::GetControlType() const { return control_type; } - -render::RenderObject* Window::GetRenderObject() const { - return render_object_.get(); -} - -void Window::OnAddChild(Control* child, Index position) { - render_object_->AddChild(child->GetRenderObject(), position); -} - -void Window::OnRemoveChild(Control* child, Index position) { - CRU_UNUSED(child); - render_object_->RemoveChild(position); -} -} // namespace cru::ui diff --git a/src/ui/controls/Button.cpp b/src/ui/controls/Button.cpp index 5f7ed143..b7407ec2 100644 --- a/src/ui/controls/Button.cpp +++ b/src/ui/controls/Button.cpp @@ -5,9 +5,9 @@ #include "cru/platform/graphics/Brush.hpp" #include "cru/platform/gui/Cursor.hpp" #include "cru/platform/gui/UiApplication.hpp" -#include "cru/ui/render/BorderRenderObject.hpp" #include "cru/ui/UiManager.hpp" -#include "cru/ui/Window.hpp" +#include "cru/ui/helper/ClickDetector.hpp" +#include "cru/ui/render/BorderRenderObject.hpp" namespace cru::ui::controls { using cru::platform::gui::SystemCursorType; @@ -21,8 +21,7 @@ void Set(render::BorderRenderObject* o, const ButtonStateStyle& s) { o->SetBackgroundBrush(s.background_brush); } -std::shared_ptr GetSystemCursor( - SystemCursorType type) { +std::shared_ptr GetSystemCursor(SystemCursorType type) { return GetUiApplication()->GetCursorManager()->GetSystemCursor(type); } } // namespace @@ -36,21 +35,21 @@ Button::Button() : click_detector_(this) { render_object_->SetBorderEnabled(true); click_detector_.StateChangeEvent()->AddHandler( - [this](const ClickState& state) { + [this](const helper::ClickState& state) { switch (state) { - case ClickState::None: + case helper::ClickState::None: Set(render_object_.get(), style_.normal); SetCursor(GetSystemCursor(SystemCursorType::Arrow)); break; - case ClickState::Hover: + case helper::ClickState::Hover: Set(render_object_.get(), style_.hover); SetCursor(GetSystemCursor(SystemCursorType::Hand)); break; - case ClickState::Press: + case helper::ClickState::Press: Set(render_object_.get(), style_.press); SetCursor(GetSystemCursor(SystemCursorType::Hand)); break; - case ClickState::PressInactive: + case helper::ClickState::PressInactive: Set(render_object_.get(), style_.press_cancel); SetCursor(GetSystemCursor(SystemCursorType::Arrow)); break; diff --git a/src/ui/controls/ContentControl.cpp b/src/ui/controls/ContentControl.cpp new file mode 100644 index 00000000..653882c0 --- /dev/null +++ b/src/ui/controls/ContentControl.cpp @@ -0,0 +1,25 @@ +#include "cru/ui/controls/ContentControl.hpp" + +namespace cru::ui::controls { +Control* ContentControl::GetChild() const { + if (GetChildren().empty()) return nullptr; + return GetChildren()[0]; +} + +void ContentControl::SetChild(Control* child) { + Control* old_child = nullptr; + if (!GetChildren().empty()) { + old_child = GetChildren()[0]; + this->RemoveChild(0); + } + if (child) { + this->AddChild(child, 0); + } + OnChildChanged(old_child, child); +} + +void ContentControl::OnChildChanged(Control* old_child, Control* new_child) { + CRU_UNUSED(old_child) + CRU_UNUSED(new_child) +} +} // namespace cru::ui::controls diff --git a/src/ui/controls/Control.cpp b/src/ui/controls/Control.cpp new file mode 100644 index 00000000..c1316a62 --- /dev/null +++ b/src/ui/controls/Control.cpp @@ -0,0 +1,157 @@ +#include "cru/ui/controls/Control.hpp" + +#include "cru/common/Base.hpp" +#include "cru/platform/gui/Cursor.hpp" +#include "cru/platform/gui/UiApplication.hpp" +#include "cru/ui/Base.hpp" +#include "cru/ui/host/WindowHost.hpp" +#include "cru/ui/render/RenderObject.hpp" + +#include + +namespace cru::ui::controls { +using platform::gui::ICursor; +using platform::gui::IUiApplication; +using platform::gui::SystemCursorType; + +Control::Control() { + MouseEnterEvent()->Direct()->AddHandler([this](event::MouseEventArgs&) { + this->is_mouse_over_ = true; + this->OnMouseHoverChange(true); + }); + + MouseLeaveEvent()->Direct()->AddHandler([this](event::MouseEventArgs&) { + this->is_mouse_over_ = false; + this->OnMouseHoverChange(true); + }); +} + +Control::~Control() { + for (const auto child : children_) delete child; +} + +host::WindowHost* Control::GetWindowHost() const { return window_host_; } + +void Control::TraverseDescendants( + const std::function& predicate) { + predicate(this); + for (auto c : GetChildren()) c->TraverseDescendants(predicate); +} + +bool Control::HasFocus() { + auto host = GetWindowHost(); + if (host == nullptr) return false; + + return host->GetFocusControl() == this; +} + +bool Control::CaptureMouse() { + auto host = GetWindowHost(); + if (host == nullptr) return false; + + return host->CaptureMouseFor(this); +} + +void Control::SetFocus() { + auto host = GetWindowHost(); + if (host == nullptr) return; + + host->SetFocusControl(this); +} + +bool Control::ReleaseMouse() { + auto host = GetWindowHost(); + if (host == nullptr) return false; + + return host->CaptureMouseFor(nullptr); +} + +bool Control::IsMouseCaptured() { + auto host = GetWindowHost(); + if (host == nullptr) return false; + + return host->GetMouseCaptureControl() == this; +} + +std::shared_ptr Control::GetCursor() { return cursor_; } + +std::shared_ptr Control::GetInheritedCursor() { + Control* control = this; + while (control != nullptr) { + const auto cursor = control->GetCursor(); + if (cursor != nullptr) return cursor; + control = control->GetParent(); + } + return IUiApplication::GetInstance()->GetCursorManager()->GetSystemCursor( + SystemCursorType::Arrow); +} + +void Control::SetCursor(std::shared_ptr cursor) { + cursor_ = std::move(cursor); + const auto host = GetWindowHost(); + if (host != nullptr) { + host->UpdateCursor(); + } +} + +void Control::AddChild(Control* control, const Index position) { + Expects(control->GetParent() == + nullptr); // The control already has a parent. + Expects(position >= 0); + Expects(position <= static_cast( + children_.size())); // The position is out of range. + + children_.insert(children_.cbegin() + position, control); + + const auto old_parent = control->parent_; + control->parent_ = this; + + OnAddChild(control, position); + control->OnParentChanged(old_parent, this); + + if (window_host_) + control->TraverseDescendants([this](Control* control) { + control->window_host_ = window_host_; + control->OnAttachToHost(window_host_); + }); +} + +void Control::RemoveChild(const Index position) { + Expects(position >= 0); + Expects(position < static_cast( + children_.size())); // The position is out of range. + + const auto i = children_.cbegin() + position; + const auto control = *i; + + children_.erase(i); + control->parent_ = nullptr; + + OnRemoveChild(control, position); + control->OnParentChanged(this, nullptr); + + if (window_host_) + control->TraverseDescendants([this](Control* control) { + control->window_host_ = nullptr; + control->OnDetachFromHost(window_host_); + }); +} + +void Control::OnAddChild(Control* child, Index position) { + CRU_UNUSED(child) + CRU_UNUSED(position) +} +void Control::OnRemoveChild(Control* child, Index position) { + CRU_UNUSED(child) + CRU_UNUSED(position) +} + +void Control::OnParentChanged(Control* old_parent, Control* new_parent) { + CRU_UNUSED(old_parent) + CRU_UNUSED(new_parent) +} + +void Control::OnAttachToHost(host::WindowHost* host) { CRU_UNUSED(host) } + +void Control::OnDetachFromHost(host::WindowHost* host) { CRU_UNUSED(host) } +} // namespace cru::ui::controls diff --git a/src/ui/controls/LayoutControl.cpp b/src/ui/controls/LayoutControl.cpp new file mode 100644 index 00000000..85417beb --- /dev/null +++ b/src/ui/controls/LayoutControl.cpp @@ -0,0 +1,3 @@ +#include "cru/ui/controls/LayoutControl.hpp" + +namespace cru::ui::controls {} diff --git a/src/ui/controls/NoChildControl.cpp b/src/ui/controls/NoChildControl.cpp new file mode 100644 index 00000000..c62c5819 --- /dev/null +++ b/src/ui/controls/NoChildControl.cpp @@ -0,0 +1,3 @@ +#include "cru/ui/controls/NoChildControl.hpp" + +namespace cru::ui::controls {} diff --git a/src/ui/controls/TextControlService.hpp b/src/ui/controls/TextControlService.hpp index a7e4e440..8ad95dec 100644 --- a/src/ui/controls/TextControlService.hpp +++ b/src/ui/controls/TextControlService.hpp @@ -8,10 +8,10 @@ #include "cru/platform/gui/UiApplication.hpp" #include "cru/platform/gui/Window.hpp" #include "cru/ui/Base.hpp" -#include "cru/ui/Control.hpp" #include "cru/ui/DebugFlags.hpp" -#include "cru/ui/ShortcutHub.hpp" -#include "cru/ui/UiEvent.hpp" +#include "cru/ui/controls/Control.hpp" +#include "cru/ui/events/UiEvent.hpp" +#include "cru/ui/helper/ShortcutHub.hpp" #include "cru/ui/host/WindowHost.hpp" #include "cru/ui/render/CanvasRenderObject.hpp" #include "cru/ui/render/ScrollRenderObject.hpp" @@ -472,7 +472,7 @@ class TextControlService : public Object { platform::gui::TimerAutoCanceler caret_timer_canceler_; int caret_blink_duration_ = k_default_caret_blink_duration; - ShortcutHub shortcut_hub_; + helper::ShortcutHub shortcut_hub_; // nullopt means not selecting std::optional select_down_button_; diff --git a/src/ui/controls/Window.cpp b/src/ui/controls/Window.cpp new file mode 100644 index 00000000..7ce40dfe --- /dev/null +++ b/src/ui/controls/Window.cpp @@ -0,0 +1,32 @@ +#include "cru/ui/controls/Window.hpp" + +#include "cru/common/Base.hpp" +#include "cru/ui/host/WindowHost.hpp" +#include "cru/ui/render/Base.hpp" +#include "cru/ui/render/StackLayoutRenderObject.hpp" + +namespace cru::ui::controls { +Window* Window::CreateOverlapped() { return new Window(); } + +Window::Window() : render_object_(new render::StackLayoutRenderObject()) { + render_object_->SetAttachedControl(this); + window_host_ = std::make_unique(this); +} + +Window::~Window() {} + +std::u16string_view Window::GetControlType() const { return control_type; } + +render::RenderObject* Window::GetRenderObject() const { + return render_object_.get(); +} + +void Window::OnAddChild(Control* child, Index position) { + render_object_->AddChild(child->GetRenderObject(), position); +} + +void Window::OnRemoveChild(Control* child, Index position) { + CRU_UNUSED(child); + render_object_->RemoveChild(position); +} +} // namespace cru::ui::controls diff --git a/src/ui/events/UiEvent.cpp b/src/ui/events/UiEvent.cpp new file mode 100644 index 00000000..b35f15a7 --- /dev/null +++ b/src/ui/events/UiEvent.cpp @@ -0,0 +1,10 @@ +#include "cru/ui/events/UiEvent.hpp" + +#include "cru/ui/render/RenderObject.hpp" + +namespace cru::ui::event { +Point MouseEventArgs::GetPointToContent( + render::RenderObject* render_object) const { + return render_object->FromRootToContent(GetPoint()); +} +} // namespace cru::ui::event diff --git a/src/ui/helper/ClickDetector.cpp b/src/ui/helper/ClickDetector.cpp new file mode 100644 index 00000000..4059f890 --- /dev/null +++ b/src/ui/helper/ClickDetector.cpp @@ -0,0 +1,131 @@ +#include "cru/ui/helper/ClickDetector.hpp" + +#include "cru/common/Logger.hpp" + +#include + +namespace cru::ui::helper { +ClickDetector::ClickDetector(controls::Control* control) { + Expects(control); + control_ = control; + + event_rovoker_guards_.push_back( + EventRevokerGuard(control->MouseEnterEvent()->Direct()->AddHandler( + [this](event::MouseEventArgs&) { + if (this->enable_) { + if (this->state_ == ClickState::PressInactive) { + if ((this->button_ & this->trigger_button_)) { + this->SetState(ClickState::Press); + } + } else { + this->SetState(ClickState::Hover); + } + } + }))); + + event_rovoker_guards_.push_back( + EventRevokerGuard(control->MouseLeaveEvent()->Direct()->AddHandler( + [this](event::MouseEventArgs&) { + if (this->enable_) { + if (this->state_ == ClickState::Press) { + if ((this->button_ & this->trigger_button_)) { + this->SetState(ClickState::PressInactive); + } + } else { + this->SetState(ClickState::None); + } + } + }))); + + event_rovoker_guards_.push_back( + EventRevokerGuard(control->MouseDownEvent()->Direct()->AddHandler( + [this](event::MouseButtonEventArgs& args) { + const auto button = args.GetButton(); + if (this->enable_ && (button & this->trigger_button_) && + this->state_ == ClickState::Hover) { + if (!this->control_->CaptureMouse()) { + log::TagDebug(log_tag, + u"Failed to capture mouse when begin click."); + return; + } + this->down_point_ = args.GetPoint(); + this->button_ = button; + this->SetState(ClickState::Press); + } + }))); + + event_rovoker_guards_.push_back( + EventRevokerGuard(control->MouseUpEvent()->Direct()->AddHandler( + [this](event::MouseButtonEventArgs& args) { + const auto button = args.GetButton(); + if (this->enable_ && (button & this->trigger_button_) && + button == button_) { + if (this->state_ == ClickState::Press) { + this->SetState(ClickState::Hover); + this->event_.Raise(ClickEventArgs{this->control_, + this->down_point_, + args.GetPoint(), button}); + this->control_->ReleaseMouse(); + } else if (this->state_ == ClickState::PressInactive) { + this->SetState(ClickState::None); + this->control_->ReleaseMouse(); + } + } + }))); +} // namespace cru::ui + +void ClickDetector::SetEnabled(bool enable) { + if (enable == enable_) { + return; + } + + enable_ = enable; + if (enable) { + SetState(control_->IsMouseOver() ? ClickState::Hover : ClickState::None); + } else { + if (state_ == ClickState::Press || state_ == ClickState::PressInactive) { + SetState(ClickState::None); + control_->ReleaseMouse(); + } else if (state_ == ClickState::Hover) { + SetState(ClickState::None); + } + } +} + +void ClickDetector::SetTriggerButton(MouseButton trigger_button) { + if (trigger_button == trigger_button_) { + return; + } + + trigger_button_ = trigger_button; + if ((state_ == ClickState::Press || state_ == ClickState::PressInactive) && + !(button_ & trigger_button)) { + SetState(control_->IsMouseOver() ? ClickState::Hover : ClickState::None); + control_->ReleaseMouse(); + } +} + +void ClickDetector::SetState(ClickState state) { +#ifdef CRU_DEBUG + auto to_string = [](ClickState state) -> std::u16string_view { + switch (state) { + case ClickState::None: + return u"None"; + case ClickState::Hover: + return u"Hover"; + case ClickState::Press: + return u"Press"; + case ClickState::PressInactive: + return u"PressInvactive"; + default: + UnreachableCode(); + } + }; + log::TagDebug(log_tag, u"Click state changed, new state: {}.", + to_string(state)); +#endif + + state_ = state; + state_change_event_.Raise(state); +} +} // namespace cru::ui::helper diff --git a/src/ui/helper/ShortcutHub.cpp b/src/ui/helper/ShortcutHub.cpp new file mode 100644 index 00000000..823072f2 --- /dev/null +++ b/src/ui/helper/ShortcutHub.cpp @@ -0,0 +1,120 @@ +#include "cru/ui/helper/ShortcutHub.hpp" + +#include "cru/common/Logger.hpp" +#include "cru/ui/DebugFlags.hpp" +#include "cru/ui/controls/Control.hpp" + +#include +#include +#include +#include + +namespace cru::ui::helper { +int ShortcutHub::RegisterShortcut(Shortcut shortcut) { + const int id = current_id_++; + map_[shortcut.key_bind].push_back({id, std::move(shortcut.name), + shortcut.key_bind, + std::move(shortcut.handler)}); + return id; +} + +void ShortcutHub::UnregisterShortcut(int id) { + if (id <= 0) return; + for (auto& pair : map_) { + auto& list = pair.second; + auto result = + std::find_if(list.cbegin(), list.cend(), + [id](const ShortcutInfo& info) { return info.id == id; }); + if (result != list.cend()) { + list.erase(result); + } + } +} + +std::vector ShortcutHub::GetAllShortcuts() const { + std::vector result; + + for (const auto& pair : map_) { + std::copy(pair.second.cbegin(), pair.second.cend(), + std::back_inserter(result)); + } + + return result; +} + +std::optional ShortcutHub::GetShortcut(int id) const { + for (auto& pair : map_) { + auto& list = pair.second; + auto result = + std::find_if(list.cbegin(), list.cend(), + [id](const ShortcutInfo& info) { return info.id == id; }); + if (result != list.cend()) { + return *result; + } + } + return std::nullopt; +} + +const std::vector& ShortcutHub::GetShortcutByKeyBind( + const ShortcutKeyBind& key_bind) const { + auto result = map_.find(key_bind); + if (result != map_.cend()) return result->second; + return empty_list_; +} + +void ShortcutHub::Install(controls::Control* control) { + if (!event_guard_.IsEmpty()) { + log::Error(u"Shortcut hub is already installed. Failed to install."); + return; + } + + event_guard_ += control->KeyDownEvent()->Bubble()->AddHandler( + std::bind(&ShortcutHub::OnKeyDown, this, std::placeholders::_1)); +} + +void ShortcutHub::Uninstall() { + if (event_guard_.IsEmpty()) { + log::Warn(u"Shortcut hub is not installed. Failed to uninstall."); + return; + } + + event_guard_.Clear(); +} + +void ShortcutHub::OnKeyDown(event::KeyEventArgs& event) { + ShortcutKeyBind key_bind(event.GetKeyCode(), event.GetKeyModifier()); + const auto& shortcut_list = this->GetShortcutByKeyBind(key_bind); + + if constexpr (debug_flags::shortcut) { + if (shortcut_list.empty()) { + log::Debug(u"No shortcut for key bind {}.", key_bind.ToString()); + } + log::Debug(u"Begin to handle shortcut for key bind {}.", + key_bind.ToString()); + } + + for (const auto& shortcut : shortcut_list) { + auto is_handled = shortcut.handler(); + if (is_handled) { + if constexpr (debug_flags::shortcut) { + log::Debug(u"Handle {} handled it.", shortcut.name); + } + + event.SetHandled(); + + break; + } else { + if constexpr (debug_flags::shortcut) { + log::Debug(u"Handle {} disdn't handle it.", shortcut.name); + } + } + } + + if constexpr (debug_flags::shortcut) { + if (!shortcut_list.empty()) { + log::Debug(u"End handling shortcut for key bind {}.", + key_bind.ToString()); + } + } +} +} // namespace cru::ui::helper diff --git a/src/ui/host/RoutedEventDispatch.hpp b/src/ui/host/RoutedEventDispatch.hpp index de94a598..52507fc7 100644 --- a/src/ui/host/RoutedEventDispatch.hpp +++ b/src/ui/host/RoutedEventDispatch.hpp @@ -1,8 +1,7 @@ #pragma once -#include "cru/ui/Control.hpp" - #include "cru/common/Logger.hpp" #include "cru/ui/DebugFlags.hpp" +#include "cru/ui/controls/Control.hpp" #include @@ -21,10 +20,11 @@ namespace cru::ui { // "original_sender", which is unchanged. And "args" will be perfectly forwarded // as the rest arguments. template -void DispatchEvent(const std::u16string_view& event_name, - Control* const original_sender, - event::RoutedEvent* (Control::*event_ptr)(), - Control* const last_receiver, Args&&... args) { +void DispatchEvent( + const std::u16string_view& event_name, + controls::Control* const original_sender, + event::RoutedEvent* (controls::Control::*event_ptr)(), + controls::Control* const last_receiver, Args&&... args) { CRU_UNUSED(event_name) if (original_sender == last_receiver) { @@ -36,7 +36,7 @@ void DispatchEvent(const std::u16string_view& event_name, return; } - std::vector receive_list; + std::vector receive_list; auto parent = original_sender; while (parent != last_receiver) { diff --git a/src/ui/host/WindowHost.cpp b/src/ui/host/WindowHost.cpp index e04fdf31..1702c4ed 100644 --- a/src/ui/host/WindowHost.cpp +++ b/src/ui/host/WindowHost.cpp @@ -8,7 +8,7 @@ #include "cru/platform/gui/UiApplication.hpp" #include "cru/platform/gui/Window.hpp" #include "cru/ui/DebugFlags.hpp" -#include "cru/ui/Window.hpp" +#include "cru/ui/controls/Window.hpp" #include "cru/ui/host/LayoutPaintCycler.hpp" #include "cru/ui/render/MeasureRequirement.hpp" #include "cru/ui/render/RenderObject.hpp" @@ -43,7 +43,7 @@ CRU_DEFINE_EVENT_NAME(KeyUp) } // namespace event_names namespace { -bool IsAncestor(Control* control, Control* ancestor) { +bool IsAncestor(controls::Control* control, controls::Control* ancestor) { while (control != nullptr) { if (control == ancestor) return true; control = control->GetParent(); @@ -52,8 +52,8 @@ bool IsAncestor(Control* control, Control* ancestor) { } // Ancestor at last. -std::vector GetAncestorList(Control* control) { - std::vector l; +std::vector GetAncestorList(controls::Control* control) { + std::vector l; while (control != nullptr) { l.push_back(control); control = control->GetParent(); @@ -61,7 +61,8 @@ std::vector GetAncestorList(Control* control) { return l; } -Control* FindLowestCommonAncestor(Control* left, Control* right) { +controls::Control* FindLowestCommonAncestor(controls::Control* left, + controls::Control* right) { if (left == nullptr || right == nullptr) return nullptr; auto&& left_list = GetAncestorList(left); @@ -102,13 +103,13 @@ inline void BindNativeEvent( } } // namespace -WindowHost::WindowHost(Control* root_control) +WindowHost::WindowHost(controls::Control* root_control) : root_control_(root_control), focus_control_(root_control) { const auto ui_application = IUiApplication::GetInstance(); auto native_window = ui_application->CreateWindow(nullptr); native_window_ = native_window; - root_control_->TraverseDescendants([this](Control* control) { + root_control_->TraverseDescendants([this](controls::Control* control) { control->window_host_ = this; control->OnAttachToHost(this); }); @@ -195,9 +196,9 @@ void WindowHost::Repaint() { painter->EndDraw(); } -Control* WindowHost::GetFocusControl() { return focus_control_; } +controls::Control* WindowHost::GetFocusControl() { return focus_control_; } -void WindowHost::SetFocusControl(Control* control) { +void WindowHost::SetFocusControl(controls::Control* control) { if (focus_control_ == control) return; if (control == nullptr) control = root_control_; @@ -206,13 +207,13 @@ void WindowHost::SetFocusControl(Control* control) { focus_control_ = control; DispatchEvent(event_names::LoseFocus, old_focus_control, - &Control::LoseFocusEvent, nullptr, false); + &controls::Control::LoseFocusEvent, nullptr, false); - DispatchEvent(event_names::GainFocus, control, &Control::GainFocusEvent, - nullptr, false); + DispatchEvent(event_names::GainFocus, control, + &controls::Control::GainFocusEvent, nullptr, false); } -bool WindowHost::CaptureMouseFor(Control* control) { +bool WindowHost::CaptureMouseFor(controls::Control* control) { if (!native_window_) return false; if (control == mouse_captured_control_) return true; @@ -240,7 +241,7 @@ bool WindowHost::CaptureMouseFor(Control* control) { return true; } -Control* WindowHost::GetMouseCaptureControl() { +controls::Control* WindowHost::GetMouseCaptureControl() { return mouse_captured_control_; } @@ -275,9 +276,9 @@ void WindowHost::OnNativeFocus(INativeWindow* window, focus == platform::gui::FocusChangeType::Gain ? DispatchEvent(event_names::GainFocus, focus_control_, - &Control::GainFocusEvent, nullptr, true) + &controls::Control::GainFocusEvent, nullptr, true) : DispatchEvent(event_names::LoseFocus, focus_control_, - &Control::LoseFocusEvent, nullptr, true); + &controls::Control::LoseFocusEvent, nullptr, true); } void WindowHost::OnNativeMouseEnterLeave( @@ -286,7 +287,7 @@ void WindowHost::OnNativeMouseEnterLeave( if (type == platform::gui::MouseEnterLeaveType::Leave) { DispatchEvent(event_names::MouseLeave, mouse_hover_control_, - &Control::MouseLeaveEvent, nullptr); + &controls::Control::MouseLeaveEvent, nullptr); mouse_hover_control_ = nullptr; } } @@ -306,13 +307,14 @@ void WindowHost::OnNativeMouseMove(INativeWindow* window, const Point& point) { mouse_captured_control_); bool a = IsAncestor(o, n); if (a) { - DispatchEvent(event_names::MouseLeave, o, &Control::MouseLeaveEvent, n); + DispatchEvent(event_names::MouseLeave, o, + &controls::Control::MouseLeaveEvent, n); } else { - DispatchEvent(event_names::MouseEnter, n, &Control::MouseEnterEvent, o, - point); + DispatchEvent(event_names::MouseEnter, n, + &controls::Control::MouseEnterEvent, o, point); } DispatchEvent(event_names::MouseMove, mouse_captured_control_, - &Control::MouseMoveEvent, nullptr, point); + &controls::Control::MouseMoveEvent, nullptr, point); UpdateCursor(); return; } @@ -320,7 +322,7 @@ void WindowHost::OnNativeMouseMove(INativeWindow* window, const Point& point) { DispatchMouseHoverControlChangeEvent( old_mouse_hover_control, new_mouse_hover_control, point, false, false); DispatchEvent(event_names::MouseMove, new_mouse_hover_control, - &Control::MouseMoveEvent, nullptr, point); + &controls::Control::MouseMoveEvent, nullptr, point); UpdateCursor(); } @@ -329,10 +331,11 @@ void WindowHost::OnNativeMouseDown( const platform::gui::NativeMouseButtonEventArgs& args) { CRU_UNUSED(window) - Control* control = + controls::Control* control = mouse_captured_control_ ? mouse_captured_control_ : HitTest(args.point); - DispatchEvent(event_names::MouseDown, control, &Control::MouseDownEvent, - nullptr, args.point, args.button, args.modifier); + DispatchEvent(event_names::MouseDown, control, + &controls::Control::MouseDownEvent, nullptr, args.point, + args.button, args.modifier); } void WindowHost::OnNativeMouseUp( @@ -340,44 +343,44 @@ void WindowHost::OnNativeMouseUp( const platform::gui::NativeMouseButtonEventArgs& args) { CRU_UNUSED(window) - Control* control = + controls::Control* control = mouse_captured_control_ ? mouse_captured_control_ : HitTest(args.point); - DispatchEvent(event_names::MouseUp, control, &Control::MouseUpEvent, nullptr, - args.point, args.button, args.modifier); + DispatchEvent(event_names::MouseUp, control, &controls::Control::MouseUpEvent, + nullptr, args.point, args.button, args.modifier); } void WindowHost::OnNativeKeyDown( INativeWindow* window, const platform::gui::NativeKeyEventArgs& args) { CRU_UNUSED(window) - DispatchEvent(event_names::KeyDown, focus_control_, &Control::KeyDownEvent, - nullptr, args.key, args.modifier); + DispatchEvent(event_names::KeyDown, focus_control_, + &controls::Control::KeyDownEvent, nullptr, args.key, + args.modifier); } void WindowHost::OnNativeKeyUp(INativeWindow* window, const platform::gui::NativeKeyEventArgs& args) { CRU_UNUSED(window) - DispatchEvent(event_names::KeyUp, focus_control_, &Control::KeyUpEvent, - nullptr, args.key, args.modifier); + DispatchEvent(event_names::KeyUp, focus_control_, + &controls::Control::KeyUpEvent, nullptr, args.key, + args.modifier); } -void WindowHost::DispatchMouseHoverControlChangeEvent(Control* old_control, - Control* new_control, - const Point& point, - bool no_leave, - bool no_enter) { +void WindowHost::DispatchMouseHoverControlChangeEvent( + controls::Control* old_control, controls::Control* new_control, + const Point& point, bool no_leave, bool no_enter) { if (new_control != old_control) // if the mouse-hover-on control changed { const auto lowest_common_ancestor = FindLowestCommonAncestor(old_control, new_control); if (!no_leave && old_control != nullptr) DispatchEvent(event_names::MouseLeave, old_control, - &Control::MouseLeaveEvent, + &controls::Control::MouseLeaveEvent, lowest_common_ancestor); // dispatch mouse leave event. if (!no_enter && new_control != nullptr) { DispatchEvent(event_names::MouseEnter, new_control, - &Control::MouseEnterEvent, lowest_common_ancestor, + &controls::Control::MouseEnterEvent, lowest_common_ancestor, point); // dispatch mouse enter event. } } @@ -391,7 +394,7 @@ void WindowHost::UpdateCursor() { } } -Control* WindowHost::HitTest(const Point& point) { +controls::Control* WindowHost::HitTest(const Point& point) { const auto render_object = root_render_object_->HitTest(point); if (render_object) { const auto control = render_object->GetAttachedControl(); diff --git a/src/win/gui/UiApplication.cpp b/src/win/gui/UiApplication.cpp index 5041a6c0..f4541dd0 100644 --- a/src/win/gui/UiApplication.cpp +++ b/src/win/gui/UiApplication.cpp @@ -36,8 +36,8 @@ WinUiApplication::WinUiApplication() { log::Logger::GetInstance()->AddSource( std::make_unique<::cru::platform::win::WinStdOutLoggerSource>()); - graph_factory_ = - std::make_unique(); + graph_factory_ = std::make_unique< + cru::platform::graphics::win::direct::DirectGraphFactory>(); god_window_ = std::make_unique(this); timer_manager_ = std::make_unique(god_window_.get()); @@ -99,13 +99,17 @@ std::vector WinUiApplication::GetAllWindow() { return result; } -INativeWindow* WinUiApplication::CreateWindow(INativeWindow* parent) { +INativeWindow* WinUiApplication::CreateWindow(INativeWindow* parent, + CreateWindowFlag flag) { WinNativeWindow* p = nullptr; if (parent != nullptr) { p = CheckPlatform(parent, GetPlatformId()); } return new WinNativeWindow(this, window_manager_->GetGeneralWindowClass(), - WS_OVERLAPPEDWINDOW, p); + flag & CreateWindowFlags::NoCaptionAndBorder + ? WS_POPUP + : WS_OVERLAPPEDWINDOW, + p); } cru::platform::graphics::IGraphFactory* WinUiApplication::GetGraphFactory() { -- cgit v1.2.3 From ddc6d6478f849ef10b832bc8b1d8ab7fe9454601 Mon Sep 17 00:00:00 2001 From: crupest Date: Mon, 9 Nov 2020 18:28:33 +0800 Subject: ... --- demos/main/main.cpp | 2 +- include/cru/ui/controls/Window.hpp | 8 ++++---- include/cru/ui/host/WindowHost.hpp | 13 +++++++++++-- src/ui/controls/Popup.cpp | 5 ++--- src/ui/controls/Window.cpp | 15 ++++++++------- src/ui/host/WindowHost.cpp | 31 ++++++++++++++++++++++--------- 6 files changed, 48 insertions(+), 26 deletions(-) (limited to 'demos/main/main.cpp') diff --git a/demos/main/main.cpp b/demos/main/main.cpp index dd3e31e9..2d5939f1 100644 --- a/demos/main/main.cpp +++ b/demos/main/main.cpp @@ -45,7 +45,7 @@ int main() { const auto text_box = TextBox::Create(); flex_layout->AddChild(text_box, 2); - window->GetWindowHost()->GetNativeWindow()->SetVisible(true); + window->Show(); return application->Run(); } diff --git a/include/cru/ui/controls/Window.hpp b/include/cru/ui/controls/Window.hpp index 616e2ee7..996bc75e 100644 --- a/include/cru/ui/controls/Window.hpp +++ b/include/cru/ui/controls/Window.hpp @@ -24,13 +24,13 @@ class Window final : public LayoutControl { render::RenderObject* GetRenderObject() const override; - protected: - void OnAddChild(Control* child, Index position) override; - void OnRemoveChild(Control* child, Index position) override; + // If create is false and native window is not create, it will not be created + // and shown. + void Show(bool create = true); private: std::unique_ptr window_host_; std::unique_ptr render_object_; }; -} // namespace cru::ui +} // namespace cru::ui::controls diff --git a/include/cru/ui/host/WindowHost.hpp b/include/cru/ui/host/WindowHost.hpp index 6d338df1..9fc24eb2 100644 --- a/include/cru/ui/host/WindowHost.hpp +++ b/include/cru/ui/host/WindowHost.hpp @@ -28,8 +28,7 @@ class WindowHost : public Object { CRU_DEFINE_CLASS_LOG_TAG(u"cru::ui::host::WindowHost") public: - WindowHost(controls::Control* root_control, - CreateWindowParams create_window_params = {}); + WindowHost(controls::Control* root_control); CRU_DELETE_COPY(WindowHost) CRU_DELETE_MOVE(WindowHost) @@ -39,6 +38,10 @@ class WindowHost : public Object { public: platform::gui::INativeWindow* GetNativeWindow() { return native_window_; } + // Do nothing if native window is already created. + gsl::not_null CreateNativeWindow( + CreateWindowParams create_window_params = {}); + // Mark the layout as invalid, and arrange a re-layout later. // This method could be called more than one times in a message cycle. But // layout only takes place once. @@ -102,6 +105,10 @@ class WindowHost : public Object { void UpdateCursor(); + IEvent* NativeWindowChangeEvent() { + return &native_window_change_event_; + } + private: //*************** region: native messages *************** void OnNativeDestroy(platform::gui::INativeWindow* window, std::nullptr_t); @@ -152,5 +159,7 @@ class WindowHost : public Object { controls::Control* mouse_captured_control_ = nullptr; bool layout_prefer_to_fill_window_ = true; + + Event native_window_change_event_; }; } // namespace cru::ui::host diff --git a/src/ui/controls/Popup.cpp b/src/ui/controls/Popup.cpp index f51f2b3b..982aee38 100644 --- a/src/ui/controls/Popup.cpp +++ b/src/ui/controls/Popup.cpp @@ -9,11 +9,10 @@ namespace cru::ui::controls { Popup::Popup(Control* attached_control) : attached_control_(attached_control) { render_object_ = std::make_unique(); + render_object_->SetAttachedControl(this); SetContainerRenderObject(render_object_.get()); - window_host_ = std::make_unique( - this, host::CreateWindowParams( - nullptr, platform::gui::CreateWindowFlags::NoCaptionAndBorder)); + window_host_ = std::make_unique(this); } Popup::~Popup() = default; diff --git a/src/ui/controls/Window.cpp b/src/ui/controls/Window.cpp index 7ce40dfe..b302cb62 100644 --- a/src/ui/controls/Window.cpp +++ b/src/ui/controls/Window.cpp @@ -1,6 +1,7 @@ #include "cru/ui/controls/Window.hpp" #include "cru/common/Base.hpp" +#include "cru/platform/gui/Base.hpp" #include "cru/ui/host/WindowHost.hpp" #include "cru/ui/render/Base.hpp" #include "cru/ui/render/StackLayoutRenderObject.hpp" @@ -10,6 +11,7 @@ Window* Window::CreateOverlapped() { return new Window(); } Window::Window() : render_object_(new render::StackLayoutRenderObject()) { render_object_->SetAttachedControl(this); + SetContainerRenderObject(render_object_.get()); window_host_ = std::make_unique(this); } @@ -21,12 +23,11 @@ render::RenderObject* Window::GetRenderObject() const { return render_object_.get(); } -void Window::OnAddChild(Control* child, Index position) { - render_object_->AddChild(child->GetRenderObject(), position); -} - -void Window::OnRemoveChild(Control* child, Index position) { - CRU_UNUSED(child); - render_object_->RemoveChild(position); +void Window::Show(bool create) { + platform::gui::INativeWindow* native_window = + create ? window_host_->CreateNativeWindow().get() + : window_host_->GetNativeWindow(); + if (!native_window) return; + native_window->SetVisible(true); } } // namespace cru::ui::controls diff --git a/src/ui/host/WindowHost.cpp b/src/ui/host/WindowHost.cpp index 95de51c2..4bd981c2 100644 --- a/src/ui/host/WindowHost.cpp +++ b/src/ui/host/WindowHost.cpp @@ -103,14 +103,8 @@ inline void BindNativeEvent( } } // namespace -WindowHost::WindowHost(controls::Control* root_control, - CreateWindowParams create_window_params) +WindowHost::WindowHost(controls::Control* root_control) : root_control_(root_control), focus_control_(root_control) { - const auto ui_application = IUiApplication::GetInstance(); - auto native_window = ui_application->CreateWindow(create_window_params.parent, - create_window_params.flag); - native_window_ = native_window; - root_control_->TraverseDescendants([this](controls::Control* control) { control->window_host_ = this; control->OnAttachToHost(this); @@ -120,6 +114,20 @@ WindowHost::WindowHost(controls::Control* root_control, root_render_object_->SetWindowHostRecursive(this); this->layout_paint_cycler_ = std::make_unique(this); +} + +WindowHost::~WindowHost() {} + +gsl::not_null WindowHost::CreateNativeWindow( + CreateWindowParams create_window_params) { + if (native_window_ != nullptr) return native_window_; + + const auto ui_application = IUiApplication::GetInstance(); + + auto native_window = ui_application->CreateWindow(create_window_params.parent, + create_window_params.flag); + + native_window_ = native_window; BindNativeEvent(this, native_window, native_window->DestroyEvent(), &WindowHost::OnNativeDestroy, event_revoker_guards_); @@ -141,9 +149,11 @@ WindowHost::WindowHost(controls::Control* root_control, &WindowHost::OnNativeKeyDown, event_revoker_guards_); BindNativeEvent(this, native_window, native_window->KeyUpEvent(), &WindowHost::OnNativeKeyUp, event_revoker_guards_); -} -WindowHost::~WindowHost() {} + native_window_change_event_.Raise(native_window); + + return native_window_; +} void WindowHost::InvalidatePaint() { layout_paint_cycler_->InvalidatePaint(); } @@ -254,6 +264,9 @@ void WindowHost::RunAfterLayoutStable(std::function action) { void WindowHost::OnNativeDestroy(INativeWindow* window, std::nullptr_t) { CRU_UNUSED(window) this->native_window_ = nullptr; + event_revoker_guards_.clear(); + + native_window_change_event_.Raise(nullptr); } void WindowHost::OnNativePaint(INativeWindow* window, std::nullptr_t) { -- cgit v1.2.3 From 68fc33443981fcd499dfe263c228787e213ae943 Mon Sep 17 00:00:00 2001 From: crupest Date: Mon, 9 Nov 2020 20:06:04 +0800 Subject: ... --- demos/main/main.cpp | 2 +- include/cru/ui/controls/Popup.hpp | 17 +++++++------ include/cru/ui/controls/RootControl.hpp | 40 +++++++++++++++++++++++++++++ include/cru/ui/controls/Window.hpp | 34 +++++++++++-------------- src/ui/CMakeLists.txt | 2 ++ src/ui/controls/Popup.cpp | 15 ++++++----- src/ui/controls/RootControl.cpp | 45 +++++++++++++++++++++++++++++++++ src/ui/controls/Window.cpp | 27 +++++++------------- 8 files changed, 130 insertions(+), 52 deletions(-) create mode 100644 include/cru/ui/controls/RootControl.hpp create mode 100644 src/ui/controls/RootControl.cpp (limited to 'demos/main/main.cpp') diff --git a/demos/main/main.cpp b/demos/main/main.cpp index 2d5939f1..66354289 100644 --- a/demos/main/main.cpp +++ b/demos/main/main.cpp @@ -23,7 +23,7 @@ int main() { auto application = CreateUiApplication(); - const auto window = Window::CreateOverlapped(); + const auto window = Window::Create(); const auto flex_layout = FlexLayout::Create(); flex_layout->SetFlexDirection(cru::ui::FlexDirection::Vertical); diff --git a/include/cru/ui/controls/Popup.hpp b/include/cru/ui/controls/Popup.hpp index f17cd1b2..d76e1211 100644 --- a/include/cru/ui/controls/Popup.hpp +++ b/include/cru/ui/controls/Popup.hpp @@ -1,10 +1,13 @@ #pragma once -#include "LayoutControl.hpp" +#include "RootControl.hpp" + +#include "cru/ui/Base.hpp" +#include "cru/platform/gui/Base.hpp" #include namespace cru::ui::controls { -class Popup : public LayoutControl { +class Popup : public RootControl { public: explicit Popup(Control* attached_control = nullptr); @@ -13,11 +16,9 @@ class Popup : public LayoutControl { ~Popup() override; - private: - std::unique_ptr window_host_; - - std::unique_ptr render_object_; - - Control* attached_control_; + protected: + gsl::not_null CreateNativeWindow( + gsl::not_null host, + platform::gui::INativeWindow* parent) override; }; } // namespace cru::ui::controls diff --git a/include/cru/ui/controls/RootControl.hpp b/include/cru/ui/controls/RootControl.hpp new file mode 100644 index 00000000..ff1b545a --- /dev/null +++ b/include/cru/ui/controls/RootControl.hpp @@ -0,0 +1,40 @@ +#pragma once +#include "LayoutControl.hpp" + +#include "cru/common/Base.hpp" +#include "cru/platform/gui/Base.hpp" +#include "cru/ui/Base.hpp" + +namespace cru::ui::controls { +class RootControl : public LayoutControl { + protected: + explicit RootControl(Control* attached_control); + + public: + CRU_DELETE_COPY(RootControl) + CRU_DELETE_MOVE(RootControl) + ~RootControl() override; + + public: + render::RenderObject* GetRenderObject() const override; + + // If create is false and native window is not create, it will not be created + // and shown. + void Show(bool create = true); + + protected: + virtual gsl::not_null CreateNativeWindow( + gsl::not_null host, + platform::gui::INativeWindow* parent) = 0; + + private: + platform::gui::INativeWindow* GetNativeWindow(bool create); + + private: + std::unique_ptr window_host_; + + std::unique_ptr render_object_; + + Control* attached_control_; +}; +} // namespace cru::ui::controls diff --git a/include/cru/ui/controls/Window.hpp b/include/cru/ui/controls/Window.hpp index 996bc75e..cca56b64 100644 --- a/include/cru/ui/controls/Window.hpp +++ b/include/cru/ui/controls/Window.hpp @@ -1,36 +1,32 @@ #pragma once -#include "LayoutControl.hpp" +#include "cru/platform/gui/Base.hpp" +#include "cru/ui/controls/RootControl.hpp" + +#include "cru/common/Base.hpp" namespace cru::ui::controls { -class Window final : public LayoutControl { +class Window final : public RootControl { public: static constexpr std::u16string_view control_type = u"Window"; public: - static Window* CreateOverlapped(); + static Window* Create(Control* attached_control = nullptr); private: - Window(); + explicit Window(Control* attached_control); public: - Window(const Window& other) = delete; - Window(Window&& other) = delete; - Window& operator=(const Window& other) = delete; - Window& operator=(Window&& other) = delete; + CRU_DELETE_COPY(Window) + CRU_DELETE_MOVE(Window) + ~Window() override; public: - std::u16string_view GetControlType() const final; - - render::RenderObject* GetRenderObject() const override; - - // If create is false and native window is not create, it will not be created - // and shown. - void Show(bool create = true); - - private: - std::unique_ptr window_host_; + std::u16string_view GetControlType() const final { return control_type; } - std::unique_ptr render_object_; + protected: + gsl::not_null CreateNativeWindow( + gsl::not_null host, + platform::gui::INativeWindow* parent) override; }; } // namespace cru::ui::controls diff --git a/src/ui/CMakeLists.txt b/src/ui/CMakeLists.txt index 15ad1258..d9edf49e 100644 --- a/src/ui/CMakeLists.txt +++ b/src/ui/CMakeLists.txt @@ -14,6 +14,7 @@ add_library(cru_ui STATIC controls/LayoutControl.cpp controls/NoChildControl.cpp controls/Popup.cpp + controls/RootControl.cpp controls/StackLayout.cpp controls/TextBlock.cpp controls/TextBox.cpp @@ -46,6 +47,7 @@ target_sources(cru_ui PUBLIC ${CRU_UI_INCLUDE_DIR}/controls/LayoutControl.hpp ${CRU_UI_INCLUDE_DIR}/controls/NoChildControl.hpp ${CRU_UI_INCLUDE_DIR}/controls/Popup.hpp + ${CRU_UI_INCLUDE_DIR}/controls/RootControl.hpp ${CRU_UI_INCLUDE_DIR}/controls/StackLayout.hpp ${CRU_UI_INCLUDE_DIR}/controls/TextBox.hpp ${CRU_UI_INCLUDE_DIR}/controls/TextBlock.hpp diff --git a/src/ui/controls/Popup.cpp b/src/ui/controls/Popup.cpp index 982aee38..bc217bf5 100644 --- a/src/ui/controls/Popup.cpp +++ b/src/ui/controls/Popup.cpp @@ -1,19 +1,22 @@ #include "cru/ui/controls/Popup.hpp" #include "cru/platform/gui/UiApplication.hpp" +#include "cru/ui/controls/RootControl.hpp" #include "cru/ui/host/WindowHost.hpp" #include "cru/ui/render/StackLayoutRenderObject.hpp" #include namespace cru::ui::controls { -Popup::Popup(Control* attached_control) : attached_control_(attached_control) { - render_object_ = std::make_unique(); - render_object_->SetAttachedControl(this); - SetContainerRenderObject(render_object_.get()); +Popup::Popup(Control* attached_control) : RootControl(attached_control) {} - window_host_ = std::make_unique(this); +Popup::~Popup() = default; + +gsl::not_null Popup::CreateNativeWindow( + gsl::not_null host, + platform::gui::INativeWindow* parent) { + return host->CreateNativeWindow( + {parent, platform::gui::CreateWindowFlags::NoCaptionAndBorder}); } -Popup::~Popup() = default; } // namespace cru::ui::controls diff --git a/src/ui/controls/RootControl.cpp b/src/ui/controls/RootControl.cpp new file mode 100644 index 00000000..61d272f8 --- /dev/null +++ b/src/ui/controls/RootControl.cpp @@ -0,0 +1,45 @@ +#include "cru/ui/controls/RootControl.hpp" + +#include "cru/common/Base.hpp" +#include "cru/platform/gui/Base.hpp" +#include "cru/ui/host/WindowHost.hpp" +#include "cru/ui/render/Base.hpp" +#include "cru/ui/render/StackLayoutRenderObject.hpp" +#include "gsl/pointers" + +#include + +namespace cru::ui::controls { +RootControl::RootControl(Control* attached_control) + : attached_control_(attached_control) { + render_object_ = std::make_unique(); + render_object_->SetAttachedControl(this); + SetContainerRenderObject(render_object_.get()); + window_host_ = std::make_unique(this); +} + +RootControl::~RootControl() {} + +render::RenderObject* RootControl::GetRenderObject() const { + return render_object_.get(); +} + +void RootControl::Show(bool create) { + platform::gui::INativeWindow* native_window = GetNativeWindow(create); + if (!native_window) return; + native_window->SetVisible(true); +} + +platform::gui::INativeWindow* RootControl::GetNativeWindow(bool create) { + const auto host = GetWindowHost(); + platform::gui::INativeWindow* native_window = host->GetNativeWindow(); + if (!create) return native_window; + if (!native_window) { + native_window = this->CreateNativeWindow( + host, attached_control_ + ? attached_control_->GetWindowHost()->GetNativeWindow() + : nullptr); + } + return native_window; +} +} // namespace cru::ui::controls diff --git a/src/ui/controls/Window.cpp b/src/ui/controls/Window.cpp index b302cb62..ba66f42e 100644 --- a/src/ui/controls/Window.cpp +++ b/src/ui/controls/Window.cpp @@ -2,32 +2,23 @@ #include "cru/common/Base.hpp" #include "cru/platform/gui/Base.hpp" +#include "cru/ui/controls/RootControl.hpp" #include "cru/ui/host/WindowHost.hpp" #include "cru/ui/render/Base.hpp" #include "cru/ui/render/StackLayoutRenderObject.hpp" namespace cru::ui::controls { -Window* Window::CreateOverlapped() { return new Window(); } - -Window::Window() : render_object_(new render::StackLayoutRenderObject()) { - render_object_->SetAttachedControl(this); - SetContainerRenderObject(render_object_.get()); - window_host_ = std::make_unique(this); +Window* Window::Create(Control* attached_control) { + return new Window(attached_control); } -Window::~Window() {} - -std::u16string_view Window::GetControlType() const { return control_type; } +Window::Window(Control* attached_control) : RootControl(attached_control) {} -render::RenderObject* Window::GetRenderObject() const { - return render_object_.get(); -} +Window::~Window() {} -void Window::Show(bool create) { - platform::gui::INativeWindow* native_window = - create ? window_host_->CreateNativeWindow().get() - : window_host_->GetNativeWindow(); - if (!native_window) return; - native_window->SetVisible(true); +gsl::not_null Window::CreateNativeWindow( + gsl::not_null host, + platform::gui::INativeWindow* parent) { + return host->CreateNativeWindow({parent}); } } // namespace cru::ui::controls -- cgit v1.2.3 From 02ed6999e9db0c20c3f55ab9c695f939aacb110c Mon Sep 17 00:00:00 2001 From: crupest Date: Tue, 10 Nov 2020 15:12:19 +0800 Subject: ... --- demos/main/main.cpp | 6 ++---- include/cru/ui/controls/TextBlock.hpp | 6 +++++- src/ui/controls/TextBlock.cpp | 19 ++++++++++++++++--- 3 files changed, 23 insertions(+), 8 deletions(-) (limited to 'demos/main/main.cpp') diff --git a/demos/main/main.cpp b/demos/main/main.cpp index 66354289..541a2320 100644 --- a/demos/main/main.cpp +++ b/demos/main/main.cpp @@ -32,12 +32,10 @@ int main() { window->AddChild(flex_layout, 0); - const auto text_block = TextBlock::Create(); - text_block->SetText(u"Hello World from CruUI!"); + const auto text_block = TextBlock::Create(u"Hello World from CruUI!", true); flex_layout->AddChild(text_block, 0); - const auto button_text_block = TextBlock::Create(); - button_text_block->SetText(u"OK"); + const auto button_text_block = TextBlock::Create(u"OK"); const auto button = Button::Create(); button->SetChild(button_text_block); flex_layout->AddChild(button, 1); diff --git a/include/cru/ui/controls/TextBlock.hpp b/include/cru/ui/controls/TextBlock.hpp index fdfdb2fa..66ebe476 100644 --- a/include/cru/ui/controls/TextBlock.hpp +++ b/include/cru/ui/controls/TextBlock.hpp @@ -9,7 +9,8 @@ class TextBlock : public NoChildControl { public: static constexpr std::u16string_view control_type = u"TextBlock"; - static TextBlock* Create() { return new TextBlock(); } + static TextBlock* Create(); + static TextBlock* Create(std::u16string text, bool selectable = false); protected: TextBlock(); @@ -28,6 +29,9 @@ class TextBlock : public NoChildControl { std::u16string GetText() const; void SetText(std::u16string text); + bool IsSelectable() const; + void SetSelectable(bool value); + gsl::not_null GetTextRenderObject(); render::ScrollRenderObject* GetScrollRenderObject() { return nullptr; } diff --git a/src/ui/controls/TextBlock.cpp b/src/ui/controls/TextBlock.cpp index 9ce99ab6..1a432582 100644 --- a/src/ui/controls/TextBlock.cpp +++ b/src/ui/controls/TextBlock.cpp @@ -7,10 +7,17 @@ #include "cru/ui/render/TextRenderObject.hpp" namespace cru::ui::controls { -using render::CanvasRenderObject; -using render::StackLayoutRenderObject; using render::TextRenderObject; +TextBlock* TextBlock::Create() { return new TextBlock(); } + +TextBlock* TextBlock::Create(std::u16string text, bool selectable) { + auto c = new TextBlock(); + c->SetText(text); + c->SetSelectable(selectable); + return c; +} + TextBlock::TextBlock() { const auto theme_resources = UiManager::GetInstance()->GetThemeResources(); @@ -21,7 +28,9 @@ TextBlock::TextBlock() { text_render_object_->SetAttachedControl(this); service_ = std::make_unique>(this); - service_->SetEnabled(true); + + service_->SetEnabled(false); + service_->SetEditable(false); } TextBlock::~TextBlock() = default; @@ -36,6 +45,10 @@ void TextBlock::SetText(std::u16string text) { service_->SetText(std::move(text)); } +bool TextBlock::IsSelectable() const { return service_->IsEnabled(); } + +void TextBlock::SetSelectable(bool value) { service_->SetEnabled(value); } + gsl::not_null TextBlock::GetTextRenderObject() { return text_render_object_.get(); } -- cgit v1.2.3