From 6aa2201797a9ed64ce0178215ae941d0c5f09579 Mon Sep 17 00:00:00 2001 From: crupest Date: Fri, 30 Oct 2020 00:07:57 +0800 Subject: ... --- 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 +++++++++++++ 6 files changed, 434 insertions(+) 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 (limited to 'include/cru/platform/gui') 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 -- cgit v1.2.3 From 9c9a9c988b5d03642f931341c97b672d054936c8 Mon Sep 17 00:00:00 2001 From: crupest Date: Fri, 30 Oct 2020 00:20:52 +0800 Subject: ... --- include/cru/platform/gui/DebugFlags.hpp | 8 ++++++++ src/win/gui/InputMethod.cpp | 7 +++++-- src/win/gui/Window.cpp | 9 +++++++-- 3 files changed, 20 insertions(+), 4 deletions(-) create mode 100644 include/cru/platform/gui/DebugFlags.hpp (limited to 'include/cru/platform/gui') diff --git a/include/cru/platform/gui/DebugFlags.hpp b/include/cru/platform/gui/DebugFlags.hpp new file mode 100644 index 00000000..2b7c7c19 --- /dev/null +++ b/include/cru/platform/gui/DebugFlags.hpp @@ -0,0 +1,8 @@ +#pragma once + +namespace cru::platform::gui { +struct DebugFlags { + static constexpr int paint = 0; + static constexpr int input_method = 0; +}; +} // namespace cru::platform::gui diff --git a/src/win/gui/InputMethod.cpp b/src/win/gui/InputMethod.cpp index d6f2146d..34638516 100644 --- a/src/win/gui/InputMethod.cpp +++ b/src/win/gui/InputMethod.cpp @@ -3,6 +3,7 @@ #include "cru/common/Logger.hpp" #include "cru/common/StringUtil.hpp" #include "cru/platform/Check.hpp" +#include "cru/platform/gui/DebugFlags.hpp" #include "cru/win/Exception.hpp" #include "cru/win/gui/Window.hpp" @@ -246,8 +247,10 @@ void WinInputMethodContext::OnWindowNativeMessage( 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 constexpr (DebugFlags::input_method) { + 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); diff --git a/src/win/gui/Window.cpp b/src/win/gui/Window.cpp index dda8a36a..174b8931 100644 --- a/src/win/gui/Window.cpp +++ b/src/win/gui/Window.cpp @@ -4,6 +4,7 @@ #include "cru/common/Logger.hpp" #include "cru/platform/Check.hpp" #include "cru/platform/gui/Base.hpp" +#include "cru/platform/gui/DebugFlags.hpp" #include "cru/win/graphics/direct/WindowPainter.hpp" #include "cru/win/gui/Cursor.hpp" #include "cru/win/gui/Exception.hpp" @@ -132,7 +133,9 @@ bool WinNativeWindow::ReleaseMouse() { } void WinNativeWindow::RequestRepaint() { - log::TagDebug(log_tag, u"A repaint is requested."); + if constexpr (DebugFlags::paint) { + log::TagDebug(log_tag, u"A repaint is requested."); + } if (!::InvalidateRect(hwnd_, nullptr, FALSE)) throw Win32Error(::GetLastError(), "Failed to invalidate window."); if (!::UpdateWindow(hwnd_)) @@ -376,7 +379,9 @@ void WinNativeWindow::OnDestroyInternal() { void WinNativeWindow::OnPaintInternal() { paint_event_.Raise(nullptr); ValidateRect(hwnd_, nullptr); - log::TagDebug(log_tag, u"A repaint is finished."); + if constexpr (DebugFlags::paint) { + log::TagDebug(log_tag, u"A repaint is finished."); + } } void WinNativeWindow::OnResizeInternal(const int new_width, -- cgit v1.2.3 From 93265251d56c91b05f160423077ce95339786f87 Mon Sep 17 00:00:00 2001 From: crupest Date: Fri, 30 Oct 2020 13:14:34 +0800 Subject: ... --- include/cru/platform/gui/UiApplication.hpp | 4 +++ include/cru/ui/host/LayoutPaintCycler.hpp | 39 ++++++++++++++++++++++++++++++ include/cru/ui/host/WindowHost.hpp | 8 +++++- src/ui/CMakeLists.txt | 2 ++ src/ui/host/LayoutPaintCycler.cpp | 35 +++++++++++++++++++++++++++ src/ui/host/WindowHost.cpp | 33 +++++++++++++------------ 6 files changed, 105 insertions(+), 16 deletions(-) create mode 100644 include/cru/ui/host/LayoutPaintCycler.hpp create mode 100644 src/ui/host/LayoutPaintCycler.cpp (limited to 'include/cru/platform/gui') diff --git a/include/cru/platform/gui/UiApplication.hpp b/include/cru/platform/gui/UiApplication.hpp index 6a2eb067..ff947dfc 100644 --- a/include/cru/platform/gui/UiApplication.hpp +++ b/include/cru/platform/gui/UiApplication.hpp @@ -67,6 +67,10 @@ class TimerAutoCanceler { return *this; } + TimerAutoCanceler& operator=(long long other) { + return this->operator=(TimerAutoCanceler(other)); + } + ~TimerAutoCanceler() { Reset(); } long long Release() { diff --git a/include/cru/ui/host/LayoutPaintCycler.hpp b/include/cru/ui/host/LayoutPaintCycler.hpp new file mode 100644 index 00000000..ed543afa --- /dev/null +++ b/include/cru/ui/host/LayoutPaintCycler.hpp @@ -0,0 +1,39 @@ +#pragma once +#include "../Base.hpp" + +#include "cru/platform/gui/UiApplication.hpp" + +#include + +namespace cru::ui::host { +class LayoutPaintCycler { + public: + explicit LayoutPaintCycler(WindowHost* host); + + CRU_DELETE_COPY(LayoutPaintCycler) + CRU_DELETE_MOVE(LayoutPaintCycler) + + ~LayoutPaintCycler(); + + public: + void InvalidateLayout(); + void InvalidatePaint(); + + bool IsLayoutDirty() { return layout_dirty_; } + + private: + void OnCycle(); + + private: + WindowHost* host_; + + platform::gui::TimerAutoCanceler timer_canceler_; + + bool layout_dirty_ = true; + bool paint_dirty_ = true; + + std::chrono::steady_clock::time_point last_cycle_time_; + std::chrono::steady_clock::duration cycle_threshold_ = + std::chrono::milliseconds(1000) / 144; +}; +} // namespace cru::ui::host diff --git a/include/cru/ui/host/WindowHost.hpp b/include/cru/ui/host/WindowHost.hpp index 77ed937f..81eabb52 100644 --- a/include/cru/ui/host/WindowHost.hpp +++ b/include/cru/ui/host/WindowHost.hpp @@ -7,8 +7,11 @@ #include "../render/Base.hpp" #include +#include namespace cru::ui::host { +class LayoutPaintCycler; + struct AfterLayoutEventArgs {}; // The bridge between control tree and native window. @@ -43,6 +46,8 @@ class WindowHost : public Object { void Relayout(); void Relayout(const Size& available_size); + void Repaint(); + // Is layout is invalid, wait for relayout and then run the action. Otherwist // run it right now. void RunAfterLayoutStable(std::function action); @@ -125,7 +130,8 @@ class WindowHost : public Object { platform::gui::INativeWindow* native_window_ = nullptr; - bool need_layout_ = false; + std::unique_ptr layout_paint_cycler_; + Event after_layout_event_; std::vector > after_layout_stable_action_; diff --git a/src/ui/CMakeLists.txt b/src/ui/CMakeLists.txt index d7b924cb..449fb4d9 100644 --- a/src/ui/CMakeLists.txt +++ b/src/ui/CMakeLists.txt @@ -21,6 +21,7 @@ add_library(cru_ui STATIC controls/TextBlock.cpp controls/TextBox.cpp controls/TextControlService.hpp + host/LayoutPaintCycler.cpp host/WindowHost.cpp render/BorderRenderObject.cpp render/CanvasRenderObject.cpp @@ -50,6 +51,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/LayoutPaintCycler.hpp ${CRU_UI_INCLUDE_DIR}/host/WindowHost.hpp ${CRU_UI_INCLUDE_DIR}/render/Base.hpp ${CRU_UI_INCLUDE_DIR}/render/BorderRenderObject.hpp diff --git a/src/ui/host/LayoutPaintCycler.cpp b/src/ui/host/LayoutPaintCycler.cpp new file mode 100644 index 00000000..9b319da4 --- /dev/null +++ b/src/ui/host/LayoutPaintCycler.cpp @@ -0,0 +1,35 @@ +#include "cru/ui/host/LayoutPaintCycler.hpp" +#include + +#include "../Helper.hpp" +#include "cru/ui/Base.hpp" +#include "cru/ui/host/WindowHost.hpp" + +namespace cru::ui::host { +LayoutPaintCycler::LayoutPaintCycler(WindowHost* host) : host_(host) { + timer_canceler_ = GetUiApplication()->SetInterval( + std::chrono::duration_cast( + this->cycle_threshold_), + [this] { OnCycle(); }); +} + +LayoutPaintCycler::~LayoutPaintCycler() = default; + +void LayoutPaintCycler::InvalidateLayout() { layout_dirty_ = true; } + +void LayoutPaintCycler::InvalidatePaint() { paint_dirty_ = true; } + +void LayoutPaintCycler::OnCycle() { + last_cycle_time_ = std::chrono::steady_clock::now(); + if (layout_dirty_) { + host_->Relayout(); + host_->Repaint(); + } else { + if (paint_dirty_) { + host_->Repaint(); + } + } + layout_dirty_ = true; + paint_dirty_ = true; +} +} // namespace cru::ui::host diff --git a/src/ui/host/WindowHost.cpp b/src/ui/host/WindowHost.cpp index eac247c1..e04fdf31 100644 --- a/src/ui/host/WindowHost.cpp +++ b/src/ui/host/WindowHost.cpp @@ -1,6 +1,7 @@ #include "cru/ui/host/WindowHost.hpp" #include "RoutedEventDispatch.hpp" +#include "cru/common/Base.hpp" #include "cru/common/Logger.hpp" #include "cru/platform/graphics/Painter.hpp" #include "cru/platform/gui/InputMethod.hpp" @@ -8,10 +9,12 @@ #include "cru/platform/gui/Window.hpp" #include "cru/ui/DebugFlags.hpp" #include "cru/ui/Window.hpp" +#include "cru/ui/host/LayoutPaintCycler.hpp" #include "cru/ui/render/MeasureRequirement.hpp" #include "cru/ui/render/RenderObject.hpp" #include +#include namespace cru::ui::host { using platform::gui::INativeWindow; @@ -113,6 +116,8 @@ WindowHost::WindowHost(Control* root_control) root_render_object_ = root_control->GetRenderObject(); root_render_object_->SetWindowHostRecursive(this); + this->layout_paint_cycler_ = std::make_unique(this); + BindNativeEvent(this, native_window, native_window->DestroyEvent(), &WindowHost::OnNativeDestroy, event_revoker_guards_); BindNativeEvent(this, native_window, native_window->PaintEvent(), @@ -141,13 +146,10 @@ WindowHost::~WindowHost() { } } -void WindowHost::InvalidatePaint() { - if (native_window_) native_window_->RequestRepaint(); -} +void WindowHost::InvalidatePaint() { layout_paint_cycler_->InvalidatePaint(); } void WindowHost::InvalidateLayout() { - need_layout_ = true; - this->InvalidatePaint(); + layout_paint_cycler_->InvalidateLayout(); } bool WindowHost::IsLayoutPreferToFillWindow() const { @@ -186,6 +188,13 @@ void WindowHost::Relayout(const Size& available_size) { log::TagDebug(log_tag, u"A relayout is finished."); } +void WindowHost::Repaint() { + auto painter = native_window_->BeginPaint(); + painter->Clear(colors::white); + root_render_object_->Draw(painter.get()); + painter->EndDraw(); +} + Control* WindowHost::GetFocusControl() { return focus_control_; } void WindowHost::SetFocusControl(Control* control) { @@ -236,7 +245,7 @@ Control* WindowHost::GetMouseCaptureControl() { } void WindowHost::RunAfterLayoutStable(std::function action) { - if (need_layout_) { + if (layout_paint_cycler_->IsLayoutDirty()) { after_layout_stable_action_.push_back(std::move(action)); } else { action(); @@ -249,14 +258,8 @@ void WindowHost::OnNativeDestroy(INativeWindow* window, std::nullptr_t) { } 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(); + CRU_UNUSED(window) + layout_paint_cycler_->InvalidatePaint(); } void WindowHost::OnNativeResize(INativeWindow* window, const Size& size) { @@ -397,4 +400,4 @@ Control* WindowHost::HitTest(const Point& point) { } return root_control_; } -} // namespace cru::ui +} // namespace cru::ui::host -- 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 'include/cru/platform/gui') 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 141fbebbe604eac53d12e7de11f999044e286cb6 Mon Sep 17 00:00:00 2001 From: crupest Date: Tue, 10 Nov 2020 14:42:36 +0800 Subject: ... --- include/cru/platform/gui/Base.hpp | 5 ----- include/cru/platform/gui/Cursor.hpp | 2 ++ include/cru/win/gui/Cursor.hpp | 1 + src/ui/controls/TextControlService.hpp | 5 +++++ src/win/gui/Cursor.cpp | 5 ++++- 5 files changed, 12 insertions(+), 6 deletions(-) (limited to 'include/cru/platform/gui') diff --git a/include/cru/platform/gui/Base.hpp b/include/cru/platform/gui/Base.hpp index fb196f02..7a9d1889 100644 --- a/include/cru/platform/gui/Base.hpp +++ b/include/cru/platform/gui/Base.hpp @@ -25,11 +25,6 @@ constexpr MouseButton middle{0b10}; constexpr MouseButton right{0b100}; } // namespace mouse_buttons -enum class SystemCursorType { - Arrow, - Hand, -}; - struct NativeMouseButtonEventArgs { MouseButton button; Point point; diff --git a/include/cru/platform/gui/Cursor.hpp b/include/cru/platform/gui/Cursor.hpp index 3f1679e4..316496a0 100644 --- a/include/cru/platform/gui/Cursor.hpp +++ b/include/cru/platform/gui/Cursor.hpp @@ -4,6 +4,8 @@ #include namespace cru::platform::gui { +enum class SystemCursorType { Arrow, Hand, IBeam }; + struct ICursor : virtual INativeResource {}; struct ICursorManager : virtual INativeResource { diff --git a/include/cru/win/gui/Cursor.hpp b/include/cru/win/gui/Cursor.hpp index cd13ded7..e7c76879 100644 --- a/include/cru/win/gui/Cursor.hpp +++ b/include/cru/win/gui/Cursor.hpp @@ -45,5 +45,6 @@ class WinCursorManager : public WinNativeResource, private: std::shared_ptr sys_arrow_; std::shared_ptr sys_hand_; + std::shared_ptr sys_ibeam_; }; } // namespace cru::platform::gui::win diff --git a/src/ui/controls/TextControlService.hpp b/src/ui/controls/TextControlService.hpp index 8ad95dec..92a66f5e 100644 --- a/src/ui/controls/TextControlService.hpp +++ b/src/ui/controls/TextControlService.hpp @@ -4,6 +4,7 @@ #include "cru/common/StringUtil.hpp" #include "cru/platform/graphics/Font.hpp" #include "cru/platform/graphics/Painter.hpp" +#include "cru/platform/gui/Cursor.hpp" #include "cru/platform/gui/InputMethod.hpp" #include "cru/platform/gui/UiApplication.hpp" #include "cru/platform/gui/Window.hpp" @@ -50,10 +51,14 @@ class TextControlService : public Object { if (this->caret_visible_) { this->SetupCaret(); } + this->control_->SetCursor( + GetUiApplication()->GetCursorManager()->GetSystemCursor( + platform::gui::SystemCursorType::IBeam)); } else { this->AbortSelection(); this->TearDownHandlers(); this->TearDownCaret(); + this->control_->SetCursor(nullptr); } } diff --git a/src/win/gui/Cursor.cpp b/src/win/gui/Cursor.cpp index 5f3086fa..80e8a749 100644 --- a/src/win/gui/Cursor.cpp +++ b/src/win/gui/Cursor.cpp @@ -35,7 +35,8 @@ WinCursor* LoadWinCursor(const wchar_t* name) { WinCursorManager::WinCursorManager() : sys_arrow_(LoadWinCursor(IDC_ARROW)), - sys_hand_(LoadWinCursor(IDC_HAND)) {} + sys_hand_(LoadWinCursor(IDC_HAND)), + sys_ibeam_(LoadWinCursor(IDC_IBEAM)) {} std::shared_ptr WinCursorManager::GetSystemWinCursor( SystemCursorType type) { @@ -44,6 +45,8 @@ std::shared_ptr WinCursorManager::GetSystemWinCursor( return sys_arrow_; case SystemCursorType::Hand: return sys_hand_; + case SystemCursorType::IBeam: + return sys_ibeam_; default: throw std::runtime_error("Unknown system cursor value."); } -- cgit v1.2.3 From 2d4a5df468f8bc13fbb657e010c393365ef79bda Mon Sep 17 00:00:00 2001 From: crupest Date: Tue, 10 Nov 2020 15:52:15 +0800 Subject: ... --- include/cru/platform/GraphBase.hpp | 6 ++++++ include/cru/platform/gui/InputMethod.hpp | 3 ++- include/cru/ui/DebugFlags.hpp | 2 +- src/ui/controls/TextBox.cpp | 2 -- src/ui/controls/TextControlService.hpp | 26 +++++++++++++++++++++++++- src/ui/host/LayoutPaintCycler.cpp | 4 ++-- src/win/gui/InputMethod.cpp | 2 +- 7 files changed, 37 insertions(+), 8 deletions(-) (limited to 'include/cru/platform/gui') diff --git a/include/cru/platform/GraphBase.hpp b/include/cru/platform/GraphBase.hpp index 6700765e..2b40898e 100644 --- a/include/cru/platform/GraphBase.hpp +++ b/include/cru/platform/GraphBase.hpp @@ -22,6 +22,12 @@ struct Point final { return fmt::format(u"({}, {})", ToUtf16String(x), ToUtf16String(y)); } + constexpr Point& operator+=(const Point& other) { + this->x += other.x; + this->y += other.y; + return *this; + } + float x = 0; float y = 0; }; diff --git a/include/cru/platform/gui/InputMethod.hpp b/include/cru/platform/gui/InputMethod.hpp index 53a8d671..9d090eab 100644 --- a/include/cru/platform/gui/InputMethod.hpp +++ b/include/cru/platform/gui/InputMethod.hpp @@ -37,7 +37,8 @@ struct IInputMethodContext : virtual INativeResource { virtual CompositionText GetCompositionText() = 0; - // Set the candidate window lefttop. Use this method to prepare typing. + // Set the candidate window lefttop. Relative to window lefttop. Use this + // method to prepare typing. virtual void SetCandidateWindowPosition(const Point& point) = 0; // Triggered when user starts composition. diff --git a/include/cru/ui/DebugFlags.hpp b/include/cru/ui/DebugFlags.hpp index fceef081..7c600d48 100644 --- a/include/cru/ui/DebugFlags.hpp +++ b/include/cru/ui/DebugFlags.hpp @@ -4,5 +4,5 @@ namespace cru::ui::debug_flags { constexpr bool routed_event = false; constexpr bool layout = false; constexpr bool shortcut = false; -constexpr bool text_service = false; +constexpr bool text_service = true; } // namespace cru::ui::debug_flags diff --git a/src/ui/controls/TextBox.cpp b/src/ui/controls/TextBox.cpp index 4a8d6658..6ba6ecb2 100644 --- a/src/ui/controls/TextBox.cpp +++ b/src/ui/controls/TextBox.cpp @@ -10,9 +10,7 @@ namespace cru::ui::controls { using render::BorderRenderObject; -using render::CanvasRenderObject; using render::ScrollRenderObject; -using render::StackLayoutRenderObject; using render::TextRenderObject; TextBox::TextBox() diff --git a/src/ui/controls/TextControlService.hpp b/src/ui/controls/TextControlService.hpp index 92a66f5e..d50621ea 100644 --- a/src/ui/controls/TextControlService.hpp +++ b/src/ui/controls/TextControlService.hpp @@ -298,6 +298,24 @@ class TextControlService : public Object { selection.GetStart(), selection.GetEnd()); } + void UpdateInputMethodPosition() { + if (auto input_method_context = this->GetInputMethodContext()) { + Point right_bottom = + this->GetTextRenderObject()->GetTotalOffset() + + this->GetTextRenderObject()->GetCaretRect().GetRightBottom(); + right_bottom.x += 5; + right_bottom.y += 5; + + if constexpr (debug_flags::text_service) { + log::TagDebug(log_tag, + u"Calculate input method candidate window position: {}.", + right_bottom.ToDebugString()); + } + + input_method_context->SetCandidateWindowPosition(right_bottom); + } + } + template void SetupOneHandler(event::RoutedEvent* (Control::*event)(), void (TextControlService::*handler)( @@ -449,6 +467,12 @@ class TextControlService : public Object { if (text == u"\b") return; this->ReplaceSelectedText(text); }); + + host::WindowHost* window_host = control_->GetWindowHost(); + if (window_host) + input_method_context_event_guard_ += + window_host->AfterLayoutEvent()->AddHandler( + [this](auto) { this->UpdateInputMethodPosition(); }); } } @@ -481,5 +505,5 @@ class TextControlService : public Object { // nullopt means not selecting std::optional select_down_button_; -}; // namespace cru::ui::controls +}; } // namespace cru::ui::controls diff --git a/src/ui/host/LayoutPaintCycler.cpp b/src/ui/host/LayoutPaintCycler.cpp index 9b319da4..fd581e00 100644 --- a/src/ui/host/LayoutPaintCycler.cpp +++ b/src/ui/host/LayoutPaintCycler.cpp @@ -29,7 +29,7 @@ void LayoutPaintCycler::OnCycle() { host_->Repaint(); } } - layout_dirty_ = true; - paint_dirty_ = true; + layout_dirty_ = false; + paint_dirty_ = false; } } // namespace cru::ui::host diff --git a/src/win/gui/InputMethod.cpp b/src/win/gui/InputMethod.cpp index 492f1c2f..0ef9a403 100644 --- a/src/win/gui/InputMethod.cpp +++ b/src/win/gui/InputMethod.cpp @@ -198,7 +198,7 @@ void WinInputMethodContext::SetCandidateWindowPosition(const Point& point) { auto himc = GetHIMC(); ::CANDIDATEFORM form; - form.dwIndex = 1; + form.dwIndex = 0; form.dwStyle = CFS_CANDIDATEPOS; form.ptCurrentPos = native_window_->DipToPixel(point); -- cgit v1.2.3 From 715be3c81b96fcf87c7650501d71480a8743a984 Mon Sep 17 00:00:00 2001 From: crupest Date: Sat, 26 Dec 2020 19:39:24 +0800 Subject: ... --- include/cru/platform/gui/Keyboard.hpp | 1 + include/cru/ui/controls/TextHostControlService.hpp | 16 +- include/cru/ui/helper/ShortcutHub.hpp | 9 +- src/ui/controls/TextHostControlService.cpp | 242 ++++++++++----------- src/ui/helper/ShortcutHub.cpp | 13 +- 5 files changed, 143 insertions(+), 138 deletions(-) (limited to 'include/cru/platform/gui') diff --git a/include/cru/platform/gui/Keyboard.hpp b/include/cru/platform/gui/Keyboard.hpp index e12cccda..6c29239b 100644 --- a/include/cru/platform/gui/Keyboard.hpp +++ b/include/cru/platform/gui/Keyboard.hpp @@ -116,6 +116,7 @@ struct TagKeyModifier {}; using KeyModifier = Bitmask; struct KeyModifiers { + static constexpr KeyModifier none{0}; static constexpr KeyModifier shift{0b1}; static constexpr KeyModifier ctrl{0b10}; static constexpr KeyModifier alt{0b100}; diff --git a/include/cru/ui/controls/TextHostControlService.hpp b/include/cru/ui/controls/TextHostControlService.hpp index 0bea52c8..9e6a08bc 100644 --- a/include/cru/ui/controls/TextHostControlService.hpp +++ b/include/cru/ui/controls/TextHostControlService.hpp @@ -70,8 +70,10 @@ class TextHostControlService : public Object { void SetSelection(gsl::index caret_position); void SetSelection(TextRange selection, bool scroll_to_caret = true); - void DeleteSelectedText(); + void ChangeSelectionEnd(gsl::index new_end); + void AbortSelection(); + void DeleteSelectedText(); // If some text is selected, then they are deleted first. Then insert text // into caret position. void ReplaceSelectedText(std::u16string_view text); @@ -92,10 +94,6 @@ class TextHostControlService : public Object { void SyncTextRenderObject(); - void StartSelection(Index start); - void UpdateSelection(Index new_end); - void AbortSelection(); - void UpdateInputMethodPosition(); template @@ -106,16 +104,14 @@ class TextHostControlService : public Object { std::bind(handler, this, std::placeholders::_1)); } - void SetUpHandlers(); - void TearDownHandlers(); - void MouseMoveHandler(event::MouseEventArgs& args); void MouseDownHandler(event::MouseButtonEventArgs& args); void MouseUpHandler(event::MouseButtonEventArgs& args); - void KeyDownHandler(event::KeyEventArgs& args); void GainFocusHandler(event::FocusChangeEventArgs& args); void LoseFocusHandler(event::FocusChangeEventArgs& args); + void SetUpShortcuts(); + private: gsl::not_null control_; gsl::not_null text_host_control_; @@ -136,6 +132,6 @@ class TextHostControlService : public Object { helper::ShortcutHub shortcut_hub_; // true if left mouse is down and selecting - bool mouse_move_selecting_; + bool mouse_move_selecting_ = false; }; } // namespace cru::ui::controls diff --git a/include/cru/ui/helper/ShortcutHub.hpp b/include/cru/ui/helper/ShortcutHub.hpp index a4ff2da2..fe3414fe 100644 --- a/include/cru/ui/helper/ShortcutHub.hpp +++ b/include/cru/ui/helper/ShortcutHub.hpp @@ -19,8 +19,9 @@ namespace cru::ui::helper { class ShortcutKeyBind { public: - ShortcutKeyBind(platform::gui::KeyCode key, - platform::gui::KeyModifier modifier) + ShortcutKeyBind( + platform::gui::KeyCode key, + platform::gui::KeyModifier modifier = platform::gui::KeyModifiers::none) : key_(key), modifier_(modifier) {} CRU_DEFAULT_COPY(ShortcutKeyBind) @@ -111,6 +112,8 @@ class ShortcutHub : public Object { const std::vector& GetShortcutByKeyBind( const ShortcutKeyBind& key_bind) const; + IEvent* FallbackKeyEvent() { return &fallback_event_; } + void Install(controls::Control* control); void Uninstall(); @@ -124,6 +127,8 @@ class ShortcutHub : public Object { int current_id_ = 1; + Event fallback_event_; + EventRevokerListGuard event_guard_; }; } // namespace cru::ui::helper diff --git a/src/ui/controls/TextHostControlService.cpp b/src/ui/controls/TextHostControlService.cpp index 7126f7b7..91ec53ff 100644 --- a/src/ui/controls/TextHostControlService.cpp +++ b/src/ui/controls/TextHostControlService.cpp @@ -3,11 +3,15 @@ #include "../Helper.hpp" #include "cru/common/Logger.hpp" #include "cru/common/StringUtil.hpp" +#include "cru/platform/gui/Base.hpp" #include "cru/platform/gui/Cursor.hpp" #include "cru/platform/gui/InputMethod.hpp" +#include "cru/platform/gui/Keyboard.hpp" #include "cru/platform/gui/UiApplication.hpp" #include "cru/platform/gui/Window.hpp" +#include "cru/ui/Base.hpp" #include "cru/ui/DebugFlags.hpp" +#include "cru/ui/events/UiEvent.hpp" #include "cru/ui/helper/ShortcutHub.hpp" #include "cru/ui/host/WindowHost.hpp" #include "cru/ui/render/ScrollRenderObject.hpp" @@ -16,13 +20,27 @@ namespace cru::ui::controls { TextHostControlService::TextHostControlService(gsl::not_null control) : control_(control), - text_host_control_(dynamic_cast(control.get())) {} + text_host_control_(dynamic_cast(control.get())) { + SetUpShortcuts(); + + SetupOneHandler(&Control::MouseMoveEvent, + &TextHostControlService::MouseMoveHandler); + SetupOneHandler(&Control::MouseDownEvent, + &TextHostControlService::MouseDownHandler); + SetupOneHandler(&Control::MouseUpEvent, + &TextHostControlService::MouseUpHandler); + SetupOneHandler(&Control::GainFocusEvent, + &TextHostControlService::GainFocusHandler); + SetupOneHandler(&Control::LoseFocusEvent, + &TextHostControlService::LoseFocusHandler); + + shortcut_hub_.Install(control_); +} void TextHostControlService::SetEnabled(bool enable) { if (enable == this->enable_) return; this->enable_ = enable; if (enable) { - this->SetUpHandlers(); if (this->caret_visible_) { this->SetupCaret(); } @@ -31,7 +49,6 @@ void TextHostControlService::SetEnabled(bool enable) { platform::gui::SystemCursorType::IBeam)); } else { this->AbortSelection(); - this->TearDownHandlers(); this->TearDownCaret(); this->control_->SetCursor(nullptr); } @@ -194,6 +211,20 @@ void TextHostControlService::SetSelection(TextRange selection, } } +void TextHostControlService::ChangeSelectionEnd(Index new_end) { + auto selection = GetSelection(); + selection.ChangeEnd(new_end); + this->SetSelection(selection); +} + +void TextHostControlService::AbortSelection() { + if (this->mouse_move_selecting_) { + this->control_->ReleaseMouse(); + this->mouse_move_selecting_ = false; + } + SetSelection(GetCaretPosition()); +} + void TextHostControlService::ReplaceSelectedText(std::u16string_view text) { DeleteSelectedText(); InsertText(GetSelection().GetStart(), text); @@ -222,21 +253,6 @@ void TextHostControlService::CoerceSelection() { this->selection_ = this->selection_.CoerceInto(0, text_.size()); } -void TextHostControlService::StartSelection(Index start) { - SetSelection(start); - if constexpr (debug_flags::text_service) - log::TagDebug(log_tag, u"Text selection started, position: {}.", start); -} - -void TextHostControlService::UpdateSelection(Index new_end) { - auto selection = GetSelection(); - selection.ChangeEnd(new_end); - this->SetSelection(selection); - if constexpr (debug_flags::text_service) - log::TagDebug(log_tag, u"Text selection updated, range: {}, {}.", - selection.GetStart(), selection.GetEnd()); -} - void TextHostControlService::SyncTextRenderObject() { const auto text_render_object = this->GetTextRenderObject(); const auto composition_info = this->GetCompositionInfo(); @@ -257,14 +273,6 @@ void TextHostControlService::SyncTextRenderObject() { } } -void TextHostControlService::AbortSelection() { - if (this->mouse_move_selecting_) { - this->control_->ReleaseMouse(); - this->mouse_move_selecting_ = false; - } - this->GetTextRenderObject()->SetSelectionRange(std::nullopt); -} - void TextHostControlService::UpdateInputMethodPosition() { if (auto input_method_context = this->GetInputMethodContext()) { Point right_bottom = @@ -283,47 +291,25 @@ void TextHostControlService::UpdateInputMethodPosition() { } } -void TextHostControlService::TearDownHandlers() { - event_guard_.Clear(); - shortcut_hub_.Uninstall(); -} -void TextHostControlService::SetUpHandlers() { - Expects(event_guard_.IsEmpty()); - - SetupOneHandler(&Control::MouseMoveEvent, - &TextHostControlService::MouseMoveHandler); - SetupOneHandler(&Control::MouseDownEvent, - &TextHostControlService::MouseDownHandler); - SetupOneHandler(&Control::MouseUpEvent, - &TextHostControlService::MouseUpHandler); - SetupOneHandler(&Control::KeyDownEvent, - &TextHostControlService::KeyDownHandler); - SetupOneHandler(&Control::GainFocusEvent, - &TextHostControlService::GainFocusHandler); - SetupOneHandler(&Control::LoseFocusEvent, - &TextHostControlService::LoseFocusHandler); - - shortcut_hub_.Install(control_); -} - void TextHostControlService::MouseDownHandler( event::MouseButtonEventArgs& args) { - if (this->mouse_move_selecting_) { - return; - } else { + if (IsEnabled()) { this->control_->SetFocus(); - if (!this->control_->CaptureMouse()) return; - this->mouse_move_selecting_ = true; - const auto text_render_object = this->GetTextRenderObject(); - const auto result = text_render_object->TextHitTest( - args.GetPointToContent(text_render_object)); - const auto position = result.position + (result.trailing ? 1 : 0); - StartSelection(position); + if (args.GetButton() == mouse_buttons::left && + !this->mouse_move_selecting_) { + if (!this->control_->CaptureMouse()) return; + this->mouse_move_selecting_ = true; + const auto text_render_object = this->GetTextRenderObject(); + const auto result = text_render_object->TextHitTest( + args.GetPointToContent(text_render_object)); + const auto position = result.position + (result.trailing ? 1 : 0); + SetSelection(position); + } } } -void TextHostControlService::MouseUpHandler(event::MouseButtonEventArgs&) { - if (mouse_move_selecting_) { +void TextHostControlService::MouseUpHandler(event::MouseButtonEventArgs& args) { + if (args.GetButton() == mouse_buttons::left && mouse_move_selecting_) { this->control_->ReleaseMouse(); this->mouse_move_selecting_ = false; } @@ -335,70 +321,7 @@ void TextHostControlService::MouseMoveHandler(event::MouseEventArgs& args) { const auto result = text_render_object->TextHitTest( args.GetPointToContent(text_render_object)); const auto position = result.position + (result.trailing ? 1 : 0); - UpdateSelection(position); - } -} - -void TextHostControlService::KeyDownHandler(event::KeyEventArgs& args) { - const auto key_code = args.GetKeyCode(); - using cru::platform::gui::KeyCode; - using cru::platform::gui::KeyModifiers; - - switch (key_code) { - case KeyCode::Backspace: { - if (!IsEditable()) return; - const auto selection = GetSelection(); - if (selection.count == 0) { - SetSelection(DeleteCharPrevious(GetCaretPosition())); - } else { - this->DeleteSelectedText(); - } - } break; - case KeyCode::Delete: { - if (!IsEditable()) return; - const auto selection = GetSelection(); - if (selection.count == 0) { - DeleteChar(GetCaretPosition()); - } else { - this->DeleteSelectedText(); - } - } break; - case KeyCode::Left: { - const auto key_modifier = args.GetKeyModifier(); - const bool shift = key_modifier & KeyModifiers::shift; - auto text = this->GetTextView(); - if (shift) { - auto selection = this->GetSelection(); - gsl::index new_position; - Utf16PreviousCodePoint(text, selection.GetEnd(), &new_position); - selection.ChangeEnd(new_position); - this->SetSelection(selection); - } else { - const auto caret = this->GetCaretPosition(); - gsl::index new_position; - Utf16PreviousCodePoint(text, caret, &new_position); - this->SetSelection(new_position); - } - } break; - case KeyCode::Right: { - const auto key_modifier = args.GetKeyModifier(); - const bool shift = key_modifier & KeyModifiers::shift; - auto text = this->GetTextView(); - if (shift) { - auto selection = this->GetSelection(); - gsl::index new_position; - Utf16NextCodePoint(text, selection.GetEnd(), &new_position); - selection.ChangeEnd(new_position); - this->SetSelection(selection); - } else { - const auto caret = this->GetCaretPosition(); - gsl::index new_position; - Utf16NextCodePoint(text, caret, &new_position); - this->SetSelection(new_position); - } - } break; - default: - break; + ChangeSelectionEnd(position); } } @@ -447,4 +370,73 @@ void TextHostControlService::LoseFocusHandler( SetCaretVisible(false); SyncTextRenderObject(); } + +void TextHostControlService::SetUpShortcuts() { + using platform::gui::KeyCode; + using platform::gui::KeyModifiers; + + shortcut_hub_.RegisterShortcut(u"Backspace", KeyCode::Backspace, [this] { + if (!IsEnabled()) return false; + if (!IsEditable()) return false; + const auto selection = GetSelection(); + if (selection.count == 0) { + SetSelection(DeleteCharPrevious(GetCaretPosition())); + } else { + this->DeleteSelectedText(); + } + return true; + }); + + shortcut_hub_.RegisterShortcut(u"Delete", KeyCode::Delete, [this] { + if (!IsEnabled()) return false; + if (!IsEditable()) return false; + const auto selection = GetSelection(); + if (selection.count == 0) { + DeleteChar(GetCaretPosition()); + } else { + this->DeleteSelectedText(); + } + return true; + }); + + shortcut_hub_.RegisterShortcut(u"Left", KeyCode::Left, [this] { + auto text = this->GetTextView(); + const auto caret = this->GetCaretPosition(); + gsl::index new_position; + Utf16PreviousCodePoint(text, caret, &new_position); + this->SetSelection(new_position); + return true; + }); + + shortcut_hub_.RegisterShortcut( + u"ShiftLeft", {KeyCode::Left, KeyModifiers::shift}, [this] { + auto text = this->GetTextView(); + auto selection = this->GetSelection(); + gsl::index new_position; + Utf16PreviousCodePoint(text, selection.GetEnd(), &new_position); + selection.ChangeEnd(new_position); + this->SetSelection(selection); + return true; + }); + + shortcut_hub_.RegisterShortcut(u"Right", KeyCode::Right, [this] { + auto text = this->GetTextView(); + const auto caret = this->GetCaretPosition(); + gsl::index new_position; + Utf16NextCodePoint(text, caret, &new_position); + this->SetSelection(new_position); + return true; + }); + + shortcut_hub_.RegisterShortcut( + u"ShiftRight", {KeyCode::Right, KeyModifiers::shift}, [this] { + auto text = this->GetTextView(); + auto selection = this->GetSelection(); + gsl::index new_position; + Utf16NextCodePoint(text, selection.GetEnd(), &new_position); + selection.ChangeEnd(new_position); + this->SetSelection(selection); + return true; + }); +} } // namespace cru::ui::controls diff --git a/src/ui/helper/ShortcutHub.cpp b/src/ui/helper/ShortcutHub.cpp index 823072f2..f35ad0ef 100644 --- a/src/ui/helper/ShortcutHub.cpp +++ b/src/ui/helper/ShortcutHub.cpp @@ -85,6 +85,8 @@ void ShortcutHub::OnKeyDown(event::KeyEventArgs& event) { ShortcutKeyBind key_bind(event.GetKeyCode(), event.GetKeyModifier()); const auto& shortcut_list = this->GetShortcutByKeyBind(key_bind); + bool handled = false; + if constexpr (debug_flags::shortcut) { if (shortcut_list.empty()) { log::Debug(u"No shortcut for key bind {}.", key_bind.ToString()); @@ -100,12 +102,13 @@ void ShortcutHub::OnKeyDown(event::KeyEventArgs& event) { log::Debug(u"Handle {} handled it.", shortcut.name); } + handled = true; event.SetHandled(); break; } else { if constexpr (debug_flags::shortcut) { - log::Debug(u"Handle {} disdn't handle it.", shortcut.name); + log::Debug(u"Handle {} didn't handle it.", shortcut.name); } } } @@ -116,5 +119,13 @@ void ShortcutHub::OnKeyDown(event::KeyEventArgs& event) { key_bind.ToString()); } } + + if (!handled) { + if constexpr (debug_flags::shortcut) { + log::Debug(u"Raise fallback event for unhandled shortcut of key bind {}.", + key_bind.ToString()); + } + fallback_event_.Raise(event); + } } } // namespace cru::ui::helper -- cgit v1.2.3 From 49dfb2bc9f965b398aa12e711148696d28443eaf Mon Sep 17 00:00:00 2001 From: crupest Date: Sat, 13 Mar 2021 16:05:21 +0800 Subject: feat: Scrollbar auto collapse. --- include/cru/platform/gui/UiApplication.hpp | 5 +++++ include/cru/ui/render/ScrollBar.hpp | 7 +++++++ src/ui/render/ScrollBar.cpp | 33 ++++++++++++++++++++++++++++-- 3 files changed, 43 insertions(+), 2 deletions(-) (limited to 'include/cru/platform/gui') diff --git a/include/cru/platform/gui/UiApplication.hpp b/include/cru/platform/gui/UiApplication.hpp index ba85020a..5a5b0b13 100644 --- a/include/cru/platform/gui/UiApplication.hpp +++ b/include/cru/platform/gui/UiApplication.hpp @@ -79,6 +79,9 @@ class TimerAutoCanceler { } TimerAutoCanceler& operator=(TimerAutoCanceler&& other) { + if (&other == this) { + return *this; + } Reset(other.id_); other.id_ = 0; return *this; @@ -101,6 +104,8 @@ class TimerAutoCanceler { id_ = id; } + explicit operator bool() const { return id_; } + private: long long id_; }; diff --git a/include/cru/ui/render/ScrollBar.hpp b/include/cru/ui/render/ScrollBar.hpp index fc2910c4..7cfd2576 100644 --- a/include/cru/ui/render/ScrollBar.hpp +++ b/include/cru/ui/render/ScrollBar.hpp @@ -94,6 +94,11 @@ class ScrollBar : public Object { void SetCursor(); void RestoreCursor(); + void BeginAutoCollapseTimer(); + void StopAutoCollapseTimer(); + + void OnMouseLeave(); + protected: gsl::not_null render_object_; @@ -118,6 +123,8 @@ class ScrollBar : public Object { Event scroll_attempt_event_; std::optional> old_cursor_; + + platform::gui::TimerAutoCanceler auto_collapse_timer_canceler_; }; class HorizontalScrollBar : public ScrollBar { diff --git a/src/ui/render/ScrollBar.cpp b/src/ui/render/ScrollBar.cpp index ee4b9e0d..02e079e9 100644 --- a/src/ui/render/ScrollBar.cpp +++ b/src/ui/render/ScrollBar.cpp @@ -14,14 +14,17 @@ #include #include +#include #include #include #include namespace cru::ui::render { +using namespace std::chrono_literals; constexpr float kScrollBarCollapseThumbWidth = 2; constexpr float kScrollBarCollapsedTriggerExpandAreaWidth = 5; constexpr float kScrollBarExpandWidth = 10; +constexpr auto kScrollBarAutoCollapseDelay = 1500ms; constexpr std::array kScrollBarAreaKindList{ ScrollBarAreaKind::UpArrow, ScrollBarAreaKind::DownArrow, @@ -131,6 +134,13 @@ void ScrollBar::InstallHandlers(controls::Control* control) { if (event.GetButton() == mouse_buttons::left && move_thumb_start_) { move_thumb_start_ = std::nullopt; + + auto hit_test_result = + ExpandedHitTest(event.GetPoint(this->render_object_)); + if (!hit_test_result) { + OnMouseLeave(); + } + control->ReleaseMouse(); event.SetHandled(); return true; @@ -159,8 +169,9 @@ void ScrollBar::InstallHandlers(controls::Control* control) { ExpandedHitTest(event.GetPoint(this->render_object_)); if (hit_test_result) { SetCursor(); + StopAutoCollapseTimer(); } else { - RestoreCursor(); + OnMouseLeave(); } } else { auto trigger_expand_area = @@ -182,7 +193,9 @@ void ScrollBar::InstallHandlers(controls::Control* control) { event_guard_ += control->MouseLeaveEvent()->Bubble()->PrependShortCircuitHandler( [this](event::MouseEventArgs&) { - if (IsExpanded() && !move_thumb_start_) RestoreCursor(); + if (IsExpanded() && !move_thumb_start_) { + OnMouseLeave(); + } return false; }); } @@ -267,6 +280,22 @@ void ScrollBar::RestoreCursor() { } } +void ScrollBar::BeginAutoCollapseTimer() { + if (!auto_collapse_timer_canceler_ && IsExpanded()) { + auto_collapse_timer_canceler_ = GetUiApplication()->SetTimeout( + kScrollBarAutoCollapseDelay, [this] { this->SetExpanded(false); }); + } +} + +void ScrollBar::StopAutoCollapseTimer() { + auto_collapse_timer_canceler_.Reset(); +} + +void ScrollBar::OnMouseLeave() { + RestoreCursor(); + BeginAutoCollapseTimer(); +} + std::optional ScrollBar::ExpandedHitTest( const Point& point) { for (auto kind : kScrollBarAreaKindList) { -- cgit v1.2.3