From da7ad0ff5c5b158be69c6cf9a2c8e9fc9ef2b3cb Mon Sep 17 00:00:00 2001 From: crupest Date: Fri, 25 Dec 2020 15:38:18 +0800 Subject: ... --- include/cru/ui/controls/TextHostControlService.hpp | 141 +++++++++++++++++++++ 1 file changed, 141 insertions(+) create mode 100644 include/cru/ui/controls/TextHostControlService.hpp (limited to 'include/cru/ui/controls/TextHostControlService.hpp') diff --git a/include/cru/ui/controls/TextHostControlService.hpp b/include/cru/ui/controls/TextHostControlService.hpp new file mode 100644 index 00000000..0bea52c8 --- /dev/null +++ b/include/cru/ui/controls/TextHostControlService.hpp @@ -0,0 +1,141 @@ +#pragma once +#include "Base.hpp" + +#include "cru/platform/gui/InputMethod.hpp" +#include "cru/platform/gui/UiApplication.hpp" +#include "cru/ui/controls/Control.hpp" +#include "cru/ui/helper/ShortcutHub.hpp" + +#include +#include + +namespace cru::ui::render { +class TextRenderObject; +class ScrollRenderObject; +} // namespace cru::ui::render + +namespace cru::ui::controls { +constexpr int k_default_caret_blink_duration = 500; + +struct ITextHostControl : virtual Interface { + virtual gsl::not_null GetTextRenderObject() = 0; + // May return nullptr. + virtual render::ScrollRenderObject* GetScrollRenderObject() = 0; +}; + +class TextHostControlService : public Object { + CRU_DEFINE_CLASS_LOG_TAG(u"cru::ui::controls::TextControlService") + + public: + TextHostControlService(gsl::not_null control); + + CRU_DELETE_COPY(TextHostControlService) + CRU_DELETE_MOVE(TextHostControlService) + + ~TextHostControlService() = default; + + public: + bool IsEnabled() { return enable_; } + void SetEnabled(bool enable); + + bool IsEditable() { return this->editable_; } + void SetEditable(bool editable); + + std::u16string GetText() { return this->text_; } + std::u16string_view GetTextView() { return this->text_; } + void SetText(std::u16string text, bool stop_composition = false); + + void InsertText(gsl::index position, std::u16string_view text, + bool stop_composition = false); + void DeleteChar(gsl::index position, bool stop_composition = false); + + // Return the position of deleted character. + gsl::index DeleteCharPrevious(gsl::index position, + bool stop_composition = false); + void DeleteText(TextRange range, bool stop_composition = false); + + void CancelComposition(); + + std::optional GetCompositionInfo(); + + bool IsCaretVisible() { return caret_visible_; } + void SetCaretVisible(bool visible); + + int GetCaretBlinkDuration() { return caret_blink_duration_; } + void SetCaretBlinkDuration(int milliseconds); + + gsl::index GetCaretPosition() { return selection_.GetEnd(); } + TextRange GetSelection() { return selection_; } + + void SetSelection(gsl::index caret_position); + void SetSelection(TextRange selection, bool scroll_to_caret = true); + + void DeleteSelectedText(); + + // If some text is selected, then they are deleted first. Then insert text + // into caret position. + void ReplaceSelectedText(std::u16string_view text); + + void ScrollToCaret(); + + private: + gsl::not_null GetTextRenderObject(); + render::ScrollRenderObject* GetScrollRenderObject(); + + // May return nullptr. + platform::gui::IInputMethodContext* GetInputMethodContext(); + + void CoerceSelection(); + + void SetupCaret(); + void TearDownCaret(); + + void SyncTextRenderObject(); + + void StartSelection(Index start); + void UpdateSelection(Index new_end); + void AbortSelection(); + + void UpdateInputMethodPosition(); + + template + void SetupOneHandler(event::RoutedEvent* (Control::*event)(), + void (TextHostControlService::*handler)( + typename event::RoutedEvent::EventArgs)) { + this->event_guard_ += (this->control_->*event)()->Direct()->AddHandler( + 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); + + private: + gsl::not_null control_; + gsl::not_null text_host_control_; + + EventRevokerListGuard event_guard_; + EventRevokerListGuard input_method_context_event_guard_; + + std::u16string text_; + TextRange selection_; + + bool enable_ = false; + bool editable_ = false; + + bool caret_visible_ = false; + platform::gui::TimerAutoCanceler caret_timer_canceler_; + int caret_blink_duration_ = k_default_caret_blink_duration; + + helper::ShortcutHub shortcut_hub_; + + // true if left mouse is down and selecting + bool mouse_move_selecting_; +}; +} // namespace cru::ui::controls -- 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/ui/controls/TextHostControlService.hpp') 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 4b78e0b74f70bca2e24dc89b4fdca4dc9222c8b9 Mon Sep 17 00:00:00 2001 From: crupest Date: Sun, 28 Feb 2021 00:22:34 +0800 Subject: ... --- include/cru/platform/graphics/Factory.hpp | 8 +- include/cru/ui/controls/TextHostControlService.hpp | 2 +- include/cru/ui/events/UiEvent.hpp | 1 + include/cru/ui/render/ScrollBar.hpp | 93 ++++- include/cru/ui/render/ScrollRenderObject.hpp | 15 + src/ui/events/UiEvent.cpp | 4 + src/ui/render/ScrollBar.cpp | 446 ++++++++++++++++++--- src/ui/render/ScrollRenderObject.cpp | 33 ++ 8 files changed, 532 insertions(+), 70 deletions(-) (limited to 'include/cru/ui/controls/TextHostControlService.hpp') diff --git a/include/cru/platform/graphics/Factory.hpp b/include/cru/platform/graphics/Factory.hpp index d1b37783..f9018e13 100644 --- a/include/cru/platform/graphics/Factory.hpp +++ b/include/cru/platform/graphics/Factory.hpp @@ -21,5 +21,11 @@ struct IGraphFactory : virtual INativeResource { virtual std::unique_ptr CreateTextLayout( std::shared_ptr font, std::u16string text) = 0; + + std::unique_ptr CreateSolidColorBrush(const Color& color) { + std::unique_ptr brush = CreateSolidColorBrush(); + brush->SetColor(color); + return brush; + } }; -} // namespace cru::platform::graph +} // namespace cru::platform::graphics diff --git a/include/cru/ui/controls/TextHostControlService.hpp b/include/cru/ui/controls/TextHostControlService.hpp index 9e6a08bc..340228fe 100644 --- a/include/cru/ui/controls/TextHostControlService.hpp +++ b/include/cru/ui/controls/TextHostControlService.hpp @@ -100,7 +100,7 @@ class TextHostControlService : public Object { void SetupOneHandler(event::RoutedEvent* (Control::*event)(), void (TextHostControlService::*handler)( typename event::RoutedEvent::EventArgs)) { - this->event_guard_ += (this->control_->*event)()->Direct()->AddHandler( + this->event_guard_ += (this->control_->*event)()->Bubble()->AddHandler( std::bind(handler, this, std::placeholders::_1)); } diff --git a/include/cru/ui/events/UiEvent.hpp b/include/cru/ui/events/UiEvent.hpp index 660b33f5..22ad0150 100644 --- a/include/cru/ui/events/UiEvent.hpp +++ b/include/cru/ui/events/UiEvent.hpp @@ -84,6 +84,7 @@ class MouseEventArgs : public UiEventArgs { // This point is relative to window client lefttop. Point GetPoint() const { return point_.value_or(Point{}); } + Point GetPoint(render::RenderObject* render_target) const; Point GetPointToContent(render::RenderObject* render_target) const; private: diff --git a/include/cru/ui/render/ScrollBar.hpp b/include/cru/ui/render/ScrollBar.hpp index a9be49a3..e3dabb57 100644 --- a/include/cru/ui/render/ScrollBar.hpp +++ b/include/cru/ui/render/ScrollBar.hpp @@ -15,25 +15,27 @@ namespace cru::ui::render { class ScrollRenderObject; -enum class ScrollKind { Absolute, Page, Line }; +enum class ScrollKind { Absolute, Relative, Page, Line }; struct Scroll { Direction direction; ScrollKind kind; - float offset; + // For absolute, the new scroll position. Otherwise, offset. + float value; }; enum class ScrollBarAreaKind { UpArrow, // Line up DownArrow, // Line down - UpThumb, // Page up - DownThumb, // Page down + UpSlot, // Page up + DownSlot, // Page down Thumb }; class ScrollBar : public Object { public: - explicit ScrollBar(gsl::not_null render_object); + ScrollBar(gsl::not_null render_object, + Direction direction); CRU_DELETE_COPY(ScrollBar) CRU_DELETE_MOVE(ScrollBar) @@ -41,12 +43,15 @@ class ScrollBar : public Object { ~ScrollBar() override = default; public: + Direction GetDirection() const { return direction_; } + bool IsEnabled() const { return is_enabled_; } void SetEnabled(bool value); - void Draw(platform::graphics::IPainter* painter); + bool IsExpanded() const { return is_expanded_; } + void SetExpanded(bool value); - virtual std::optional HitTest(const Point& point) = 0; + void Draw(platform::graphics::IPainter* painter); IEvent* ScrollAttemptEvent() { return &scroll_attempt_event_; } @@ -54,20 +59,54 @@ class ScrollBar : public Object { void UninstallHandlers() { InstallHandlers(nullptr); } gsl::not_null> - GetCollapseThumbBrush() const; + GetCollapsedThumbBrush() const; + gsl::not_null> + GetExpandedThumbBrush() const; + gsl::not_null> + GetExpandedSlotBrush() const; + gsl::not_null> + GetExpandedArrowBrush() const; + gsl::not_null> + GetExpandedArrowBackgroundBrush() const; protected: - virtual void OnDraw(platform::graphics::IPainter* painter, bool expand) = 0; + void OnDraw(platform::graphics::IPainter* painter, bool expand); + + virtual void DrawUpArrow(platform::graphics::IPainter* painter, + const Rect& area) = 0; + virtual void DrawDownArrow(platform::graphics::IPainter* painter, + const Rect& area) = 0; + + std::optional ExpandedHitTest(const Point& point); + + virtual bool IsShowBar() = 0; + + virtual std::optional GetExpandedAreaRect( + ScrollBarAreaKind area_kind) = 0; + virtual std::optional GetCollapsedTriggerExpandAreaRect() = 0; + virtual std::optional GetCollapsedThumbRect() = 0; + + virtual float CalculateNewScrollPosition(const Rect& thumb_original_rect, + const Point& mouse_offset) = 0; protected: gsl::not_null render_object_; private: + Direction direction_; + bool is_enabled_ = true; bool is_expanded_ = false; - std::shared_ptr collapse_thumb_brush_; + std::shared_ptr collapsed_thumb_brush_; + std::shared_ptr expanded_thumb_brush_; + std::shared_ptr expanded_slot_brush_; + std::shared_ptr expanded_arrow_brush_; + std::shared_ptr expanded_arrow_background_brush_; + + Rect move_thumb_thumb_original_rect_; + std::optional move_thumb_start_; EventRevokerListGuard event_guard_; @@ -84,11 +123,20 @@ class HorizontalScrollBar : public ScrollBar { ~HorizontalScrollBar() override = default; - public: - std::optional HitTest(const Point& point) override; - protected: - void OnDraw(platform::graphics::IPainter* painter, bool expand) override; + void DrawUpArrow(platform::graphics::IPainter* painter, + const Rect& area) override; + void DrawDownArrow(platform::graphics::IPainter* painter, + const Rect& area) override; + + bool IsShowBar() override; + + std::optional GetExpandedAreaRect(ScrollBarAreaKind area_kind) override; + std::optional GetCollapsedTriggerExpandAreaRect() override; + std::optional GetCollapsedThumbRect() override; + + float CalculateNewScrollPosition(const Rect& thumb_original_rect, + const Point& mouse_offset) override; }; class VerticalScrollBar : public ScrollBar { @@ -100,11 +148,20 @@ class VerticalScrollBar : public ScrollBar { ~VerticalScrollBar() override = default; - public: - std::optional HitTest(const Point& point) override; - protected: - void OnDraw(platform::graphics::IPainter* painter, bool expand) override; + void DrawUpArrow(platform::graphics::IPainter* painter, + const Rect& area) override; + void DrawDownArrow(platform::graphics::IPainter* painter, + const Rect& area) override; + + bool IsShowBar() override; + + std::optional GetExpandedAreaRect(ScrollBarAreaKind area_kind) override; + std::optional GetCollapsedTriggerExpandAreaRect() override; + std::optional GetCollapsedThumbRect() override; + + float CalculateNewScrollPosition(const Rect& thumb_original_rect, + const Point& mouse_offset) override; }; // A delegate to draw scrollbar and register related events. diff --git a/include/cru/ui/render/ScrollRenderObject.hpp b/include/cru/ui/render/ScrollRenderObject.hpp index 6a6ef198..aed25f8e 100644 --- a/include/cru/ui/render/ScrollRenderObject.hpp +++ b/include/cru/ui/render/ScrollRenderObject.hpp @@ -2,6 +2,7 @@ #include "RenderObject.hpp" #include "cru/platform/graphics/util/Painter.hpp" +#include "cru/ui/Base.hpp" #include "cru/ui/render/ScrollBar.hpp" #include @@ -29,8 +30,22 @@ class ScrollRenderObject : public RenderObject { // Return the coerced scroll offset. Point GetScrollOffset(); + float GetScrollOffset(Direction direction) { + return direction == Direction::Horizontal ? GetScrollOffset().x + : GetScrollOffset().y; + } void SetScrollOffset(const Point& offset); void SetScrollOffset(std::optional x, std::optional y); + void SetScrollOffset(Direction direction, std::optional value) { + if (direction == Direction::Horizontal) { + SetScrollOffset(value, std::nullopt); + } else { + SetScrollOffset(std::nullopt, value); + } + } + + void Scroll(const Scroll& scroll); + Point GetRawScrollOffset() const { return scroll_offset_; } // Return the viewable area rect. diff --git a/src/ui/events/UiEvent.cpp b/src/ui/events/UiEvent.cpp index b35f15a7..4c75f690 100644 --- a/src/ui/events/UiEvent.cpp +++ b/src/ui/events/UiEvent.cpp @@ -3,6 +3,10 @@ #include "cru/ui/render/RenderObject.hpp" namespace cru::ui::event { +Point MouseEventArgs::GetPoint(render::RenderObject* render_object) const { + return GetPoint() - render_object->GetTotalOffset(); +} + Point MouseEventArgs::GetPointToContent( render::RenderObject* render_object) const { return render_object->FromRootToContent(GetPoint()); diff --git a/src/ui/render/ScrollBar.cpp b/src/ui/render/ScrollBar.cpp index 487f0b91..6096ab63 100644 --- a/src/ui/render/ScrollBar.cpp +++ b/src/ui/render/ScrollBar.cpp @@ -5,23 +5,44 @@ #include "cru/platform/GraphBase.hpp" #include "cru/platform/graphics/Factory.hpp" #include "cru/platform/graphics/Painter.hpp" +#include "cru/platform/gui/Base.hpp" +#include "cru/ui/Base.hpp" +#include "cru/ui/events/UiEvent.hpp" #include "cru/ui/render/ScrollRenderObject.hpp" +#include "gsl/gsl_assert" +#include +#include #include #include +#include namespace cru::ui::render { constexpr float kScrollBarCollapseThumbWidth = 2; +constexpr float kScrollBarCollapsedTriggerExpandAreaWidth = 5; +constexpr float kScrollBarExpandWidth = 10; -ScrollBar::ScrollBar(gsl::not_null render_object) - : render_object_(render_object) { +constexpr std::array kScrollBarAreaKindList{ + ScrollBarAreaKind::UpArrow, ScrollBarAreaKind::DownArrow, + ScrollBarAreaKind::UpSlot, ScrollBarAreaKind::DownSlot, + ScrollBarAreaKind::Thumb}; + +ScrollBar::ScrollBar(gsl::not_null render_object, + Direction direction) + : render_object_(render_object), direction_(direction) { // TODO: Use theme resource and delete this. - auto collapse_thumb_brush = GetUiApplication() - ->GetInstance() - ->GetGraphFactory() - ->CreateSolidColorBrush(); - collapse_thumb_brush->SetColor(colors::gray.WithAlpha(128)); - collapse_thumb_brush_ = std::move(collapse_thumb_brush); + + auto graphics_factory = GetUiApplication()->GetInstance()->GetGraphFactory(); + + collapsed_thumb_brush_ = + graphics_factory->CreateSolidColorBrush(colors::gray.WithAlpha(128)); + expanded_thumb_brush_ = graphics_factory->CreateSolidColorBrush(colors::gray); + expanded_slot_brush_ = + graphics_factory->CreateSolidColorBrush(colors::seashell); + expanded_arrow_brush_ = + graphics_factory->CreateSolidColorBrush(colors::white); + expanded_arrow_background_brush_ = + graphics_factory->CreateSolidColorBrush(colors::black); } void ScrollBar::SetEnabled(bool value) { @@ -29,6 +50,12 @@ void ScrollBar::SetEnabled(bool value) { // TODO: Implement this. } +void ScrollBar::SetExpanded(bool value) { + if (is_expanded_ == value) return; + is_expanded_ = value; + render_object_->InvalidatePaint(); +} + void ScrollBar::Draw(platform::graphics::IPainter* painter) { if (is_enabled_) { OnDraw(painter, is_expanded_); @@ -36,88 +63,407 @@ void ScrollBar::Draw(platform::graphics::IPainter* painter) { } void ScrollBar::InstallHandlers(controls::Control* control) { - CRU_UNUSED(control); - // TODO: Implement this. + event_guard_.Clear(); + if (control != nullptr) { + event_guard_ += control->MouseDownEvent()->Bubble()->AddHandler( + [control, this](event::MouseButtonEventArgs& event) { + if (event.GetButton() == mouse_buttons::left && IsEnabled() && + IsExpanded()) { + auto hit_test_result = + ExpandedHitTest(event.GetPoint(render_object_)); + if (!hit_test_result) return; + + switch (*hit_test_result) { + case ScrollBarAreaKind::UpArrow: + this->scroll_attempt_event_.Raise( + {GetDirection(), ScrollKind::Line, -1}); + event.SetHandled(); + break; + case ScrollBarAreaKind::DownArrow: + this->scroll_attempt_event_.Raise( + {GetDirection(), ScrollKind::Line, 1}); + event.SetHandled(); + break; + case ScrollBarAreaKind::UpSlot: + this->scroll_attempt_event_.Raise( + {GetDirection(), ScrollKind::Page, -1}); + event.SetHandled(); + break; + case ScrollBarAreaKind::DownSlot: + this->scroll_attempt_event_.Raise( + {GetDirection(), ScrollKind::Page, 1}); + event.SetHandled(); + break; + case ScrollBarAreaKind::Thumb: { + auto thumb_rect = GetExpandedAreaRect(ScrollBarAreaKind::Thumb); + assert(thumb_rect); + + if (!control->CaptureMouse()) break; + move_thumb_thumb_original_rect_ = *thumb_rect; + move_thumb_start_ = event.GetPoint(); + event.SetHandled(); + break; + } + default: + break; + } + } + }); + + event_guard_ += control->MouseUpEvent()->Bubble()->AddHandler( + [control, this](event::MouseButtonEventArgs& event) { + if (event.GetButton() == mouse_buttons::left && move_thumb_start_) { + move_thumb_start_ = std::nullopt; + control->ReleaseMouse(); + event.SetHandled(); + } + }); + + event_guard_ += control->MouseMoveEvent()->Bubble()->AddHandler( + [this](event::MouseEventArgs& event) { + if (move_thumb_start_) { + auto new_scroll_position = CalculateNewScrollPosition( + move_thumb_thumb_original_rect_, + event.GetPoint() - *move_thumb_start_); + + this->scroll_attempt_event_.Raise( + {GetDirection(), ScrollKind::Absolute, new_scroll_position}); + event.SetHandled(); + return; + } + + if (IsEnabled() && !IsExpanded()) { + auto trigger_expand_area = GetCollapsedTriggerExpandAreaRect(); + if (trigger_expand_area && + trigger_expand_area->IsPointInside( + event.GetPoint(this->render_object_))) + SetExpanded(true); + event.SetHandled(); + } + }); + } } gsl::not_null> -ScrollBar::GetCollapseThumbBrush() const { +ScrollBar::GetCollapsedThumbBrush() const { // TODO: Read theme resource. - return collapse_thumb_brush_; + return collapsed_thumb_brush_; } -HorizontalScrollBar::HorizontalScrollBar( - gsl::not_null render_object) - : ScrollBar(render_object) {} +gsl::not_null> +ScrollBar::GetExpandedThumbBrush() const { + // TODO: Read theme resource. + return expanded_thumb_brush_; +} + +gsl::not_null> +ScrollBar::GetExpandedSlotBrush() const { + // TODO: Read theme resource. + return expanded_slot_brush_; +} + +gsl::not_null> +ScrollBar::GetExpandedArrowBrush() const { + // TODO: Read theme resource. + return expanded_arrow_brush_; +} + +gsl::not_null> +ScrollBar::GetExpandedArrowBackgroundBrush() const { + // TODO: Read theme resource. + return expanded_arrow_brush_; +} + +void ScrollBar::OnDraw(platform::graphics::IPainter* painter, + bool is_expanded) { + if (is_expanded) { + auto thumb_rect = GetExpandedAreaRect(ScrollBarAreaKind::Thumb); + if (thumb_rect) + painter->FillRectangle(*thumb_rect, GetExpandedThumbBrush().get().get()); + + auto slot_brush = GetExpandedSlotBrush().get().get(); + + auto up_slot_rect = GetExpandedAreaRect(ScrollBarAreaKind::UpSlot); + if (up_slot_rect) painter->FillRectangle(*up_slot_rect, slot_brush); + + auto down_slot_rect = GetExpandedAreaRect(ScrollBarAreaKind::DownSlot); + if (down_slot_rect) painter->FillRectangle(*down_slot_rect, slot_brush); + + auto up_arrow = GetExpandedAreaRect(ScrollBarAreaKind::UpArrow); + if (up_arrow) this->DrawUpArrow(painter, *up_arrow); -std::optional HorizontalScrollBar::HitTest( + auto down_arrow = GetExpandedAreaRect(ScrollBarAreaKind::DownArrow); + if (down_arrow) this->DrawUpArrow(painter, *down_arrow); + } else { + auto optional_rect = GetCollapsedThumbRect(); + if (optional_rect) { + painter->FillRectangle(*optional_rect, + GetCollapsedThumbBrush().get().get()); + } + } +} + +std::optional ScrollBar::ExpandedHitTest( const Point& point) { - // TODO: Implement this. - CRU_UNUSED(point); + for (auto kind : kScrollBarAreaKindList) { + auto rect = this->GetExpandedAreaRect(kind); + if (rect) { + if (rect->IsPointInside(point)) return kind; + } + } return std::nullopt; } -void HorizontalScrollBar::OnDraw(platform::graphics::IPainter* painter, - bool expand) { +HorizontalScrollBar::HorizontalScrollBar( + gsl::not_null render_object) + : ScrollBar(render_object, Direction::Horizontal) {} + +void HorizontalScrollBar::DrawUpArrow(platform::graphics::IPainter* painter, + const Rect& area) { + // TODO: Do what you must! + painter->FillRectangle(area, GetExpandedArrowBackgroundBrush().get().get()); +} + +void HorizontalScrollBar::DrawDownArrow(platform::graphics::IPainter* painter, + const Rect& area) { + // TODO: Do what you must! + painter->FillRectangle(area, GetExpandedArrowBackgroundBrush().get().get()); +} + +bool HorizontalScrollBar::IsShowBar() { const auto child = render_object_->GetFirstChild(); - if (child == nullptr) return; + if (child == nullptr) return false; const auto view_rect = render_object_->GetViewRect(); + const auto child_size = child->GetSize(); + + if (view_rect.width >= child_size.width) return false; + + return true; +} + +std::optional HorizontalScrollBar::GetExpandedAreaRect( + ScrollBarAreaKind area_kind) { + auto show = IsShowBar(); + if (!show) return std::nullopt; + const auto padding_rect = render_object_->GetPaddingRect(); + + const auto child = render_object_->GetFirstChild(); + + const auto view_rect = render_object_->GetViewRect(); const auto child_size = child->GetSize(); - if (view_rect.width >= child_size.width) return; + const float start_percentage = view_rect.left / child_size.width; + const float length_percentage = view_rect.width / child_size.width; + const float end_percentage = start_percentage + length_percentage; + + const float top = padding_rect.GetBottom() - kScrollBarExpandWidth; + const float height = kScrollBarExpandWidth; + + // Without arrow. + const float bar_area_length = padding_rect.width - 3 * kScrollBarExpandWidth; + const float bar_area_start = padding_rect.left + kScrollBarExpandWidth; + + switch (area_kind) { + case ScrollBarAreaKind::UpArrow: + return Rect{padding_rect.left, top, kScrollBarExpandWidth, height}; + case ScrollBarAreaKind::DownArrow: + return Rect{padding_rect.GetRight() - 2 * kScrollBarExpandWidth, top, + kScrollBarExpandWidth, height}; + case ScrollBarAreaKind::UpSlot: + return Rect{bar_area_start, top, bar_area_length * start_percentage, + height}; + case ScrollBarAreaKind::DownSlot: + return Rect{bar_area_start + bar_area_length * end_percentage, top, + bar_area_length * (1 - end_percentage), height}; + case ScrollBarAreaKind::Thumb: + return Rect{bar_area_start + bar_area_length * start_percentage, top, + bar_area_length * length_percentage, height}; + default: + throw std::invalid_argument("Unsupported scroll area kind."); + } +} + +std::optional HorizontalScrollBar::GetCollapsedTriggerExpandAreaRect() { + auto show = IsShowBar(); + if (!show) return std::nullopt; + + const auto padding_rect = render_object_->GetPaddingRect(); + + return Rect{ + padding_rect.left, + padding_rect.GetBottom() - kScrollBarCollapsedTriggerExpandAreaWidth, + padding_rect.width, kScrollBarCollapseThumbWidth}; +} + +std::optional HorizontalScrollBar::GetCollapsedThumbRect() { + auto show = IsShowBar(); + if (!show) return std::nullopt; + + const auto child = render_object_->GetFirstChild(); + + const auto view_rect = render_object_->GetViewRect(); + const auto child_size = child->GetSize(); const float start_percentage = view_rect.left / child_size.width; const float length_percentage = view_rect.width / child_size.width; // const float end_percentage = start_percentage + length_percentage; - if (expand) { - // TODO: Implement this. - } else { - Rect thumb_rect{padding_rect.left + padding_rect.width * start_percentage, - padding_rect.GetBottom() - kScrollBarCollapseThumbWidth, - padding_rect.width * length_percentage, - kScrollBarCollapseThumbWidth}; - painter->FillRectangle(thumb_rect, GetCollapseThumbBrush().get().get()); - } + const auto padding_rect = render_object_->GetPaddingRect(); + + return Rect{padding_rect.left + padding_rect.width * start_percentage, + padding_rect.GetBottom() - kScrollBarCollapseThumbWidth, + padding_rect.width * length_percentage, + kScrollBarCollapseThumbWidth}; +} + +float HorizontalScrollBar::CalculateNewScrollPosition( + const Rect& thumb_original_rect, const Point& mouse_offset) { + auto new_thumb_start = thumb_original_rect.left + mouse_offset.x; + + const auto padding_rect = render_object_->GetPaddingRect(); + + auto scroll_area_start = padding_rect.left + kScrollBarExpandWidth; + auto scroll_area_end = padding_rect.GetRight() - 2 * kScrollBarExpandWidth; + + auto thumb_head_end = scroll_area_end - thumb_original_rect.width; + + const auto child = render_object_->GetFirstChild(); + const auto child_size = child->GetSize(); + + new_thumb_start = + std::clamp(new_thumb_start, scroll_area_start, thumb_head_end); + + auto offset = new_thumb_start / (scroll_area_end - scroll_area_start) * + child_size.width; + + return offset; } VerticalScrollBar::VerticalScrollBar( gsl::not_null render_object) - : ScrollBar(render_object) {} + : ScrollBar(render_object, Direction::Vertical) {} -std::optional VerticalScrollBar::HitTest( - const Point& point) { - // TODO: Implement this. - CRU_UNUSED(point); - return std::nullopt; +void VerticalScrollBar::DrawUpArrow(platform::graphics::IPainter* painter, + const Rect& area) { + // TODO: Do what you must! + painter->FillRectangle(area, GetExpandedArrowBackgroundBrush().get().get()); +} + +void VerticalScrollBar::DrawDownArrow(platform::graphics::IPainter* painter, + const Rect& area) { + // TODO: Do what you must! + painter->FillRectangle(area, GetExpandedArrowBackgroundBrush().get().get()); +} + +bool VerticalScrollBar::IsShowBar() { + const auto child = render_object_->GetFirstChild(); + if (child == nullptr) return false; + + const auto view_rect = render_object_->GetViewRect(); + const auto child_size = child->GetSize(); + + if (view_rect.height >= child_size.height) return false; + + return true; } -void VerticalScrollBar::OnDraw(platform::graphics::IPainter* painter, - bool expand) { +std::optional VerticalScrollBar::GetExpandedAreaRect( + ScrollBarAreaKind area_kind) { + auto show = IsShowBar(); + if (!show) return std::nullopt; + + const auto padding_rect = render_object_->GetPaddingRect(); + const auto child = render_object_->GetFirstChild(); - if (child == nullptr) return; + + const auto view_rect = render_object_->GetViewRect(); + const auto child_size = child->GetSize(); + + const float start_percentage = view_rect.top / child_size.height; + const float length_percentage = view_rect.height / child_size.height; + const float end_percentage = start_percentage + length_percentage; + + const float left = padding_rect.GetRight() - kScrollBarExpandWidth; + const float width = kScrollBarExpandWidth; + + // Without arrow. + const float bar_area_length = padding_rect.height - 3 * kScrollBarExpandWidth; + const float bar_area_start = padding_rect.top + kScrollBarExpandWidth; + + switch (area_kind) { + case ScrollBarAreaKind::UpArrow: + return Rect{left, padding_rect.top, width, kScrollBarExpandWidth}; + case ScrollBarAreaKind::DownArrow: + return Rect{left, padding_rect.GetBottom() - 2 * kScrollBarExpandWidth, + width, kScrollBarExpandWidth}; + case ScrollBarAreaKind::UpSlot: + return Rect{left, bar_area_start, width, + bar_area_length * start_percentage}; + case ScrollBarAreaKind::DownSlot: + return Rect{left, bar_area_start + bar_area_length * end_percentage, + width, bar_area_length * (1 - end_percentage)}; + case ScrollBarAreaKind::Thumb: + return Rect{left, bar_area_start + bar_area_length * start_percentage, + width, bar_area_length * length_percentage}; + default: + throw std::invalid_argument("Unsupported scroll area kind."); + } +} + +std::optional VerticalScrollBar::GetCollapsedTriggerExpandAreaRect() { + auto show = IsShowBar(); + if (!show) return std::nullopt; + + const auto padding_rect = render_object_->GetPaddingRect(); + + return Rect{ + padding_rect.GetRight() - kScrollBarCollapsedTriggerExpandAreaWidth, + padding_rect.top, kScrollBarCollapseThumbWidth, padding_rect.height}; +} + +std::optional VerticalScrollBar::GetCollapsedThumbRect() { + const auto child = render_object_->GetFirstChild(); + if (child == nullptr) return std::nullopt; const auto view_rect = render_object_->GetViewRect(); const auto padding_rect = render_object_->GetPaddingRect(); const auto child_size = child->GetSize(); - if (view_rect.height >= child_size.height) return; + if (view_rect.height >= child_size.height) return std::nullopt; const float start_percentage = view_rect.top / child_size.height; const float length_percentage = view_rect.height / child_size.height; // const float end_percentage = start_percentage + length_percentage; - if (expand) { - // TODO: Implement this. - } else { - Rect thumb_rect{padding_rect.GetRight() - kScrollBarCollapseThumbWidth, - padding_rect.top + padding_rect.height * start_percentage, - kScrollBarCollapseThumbWidth, - padding_rect.height * length_percentage}; - painter->FillRectangle(thumb_rect, GetCollapseThumbBrush().get().get()); - } + return Rect{padding_rect.GetRight() - kScrollBarCollapseThumbWidth, + padding_rect.top + padding_rect.height * start_percentage, + kScrollBarCollapseThumbWidth, + padding_rect.height * length_percentage}; +} + +float VerticalScrollBar::CalculateNewScrollPosition( + const Rect& thumb_original_rect, const Point& mouse_offset) { + auto new_thumb_start = thumb_original_rect.top + mouse_offset.y; + + const auto padding_rect = render_object_->GetPaddingRect(); + + auto scroll_area_start = padding_rect.top + kScrollBarExpandWidth; + auto scroll_area_end = padding_rect.GetBottom() - 2 * kScrollBarExpandWidth; + + auto thumb_head_end = scroll_area_end - thumb_original_rect.height; + + const auto child = render_object_->GetFirstChild(); + const auto child_size = child->GetSize(); + + new_thumb_start = + std::clamp(new_thumb_start, scroll_area_start, thumb_head_end); + + auto offset = new_thumb_start / (scroll_area_end - scroll_area_start) * + child_size.height; + + return offset; } ScrollBarDelegate::ScrollBarDelegate( diff --git a/src/ui/render/ScrollRenderObject.cpp b/src/ui/render/ScrollRenderObject.cpp index a9ec729d..0a81eaab 100644 --- a/src/ui/render/ScrollRenderObject.cpp +++ b/src/ui/render/ScrollRenderObject.cpp @@ -2,13 +2,17 @@ #include "cru/platform/graphics/Painter.hpp" #include "cru/platform/graphics/util/Painter.hpp" +#include "cru/ui/Base.hpp" #include "cru/ui/controls/Control.hpp" #include "cru/ui/render/ScrollBar.hpp" #include #include +#include namespace cru::ui::render { +constexpr float kLineHeight = 16; + namespace { // This method assumes margin offset is already considered. // It promises that it won't return negetive value. @@ -36,6 +40,35 @@ Point CoerceScroll(const Point& scroll_offset, const Size& content_size, ScrollRenderObject::ScrollRenderObject() : RenderObject(ChildMode::Single) { scroll_bar_delegate_ = std::make_unique(this); + scroll_bar_delegate_->ScrollAttemptEvent()->AddHandler( + [this](const struct Scroll& scroll) { this->Scroll(scroll); }); +} + +void ScrollRenderObject::Scroll(const struct Scroll& scroll) { + auto direction = scroll.direction; + + switch (scroll.kind) { + case ScrollKind::Absolute: + SetScrollOffset(direction, scroll.value); + break; + case ScrollKind::Relative: + SetScrollOffset(direction, + GetScrollOffset(scroll.direction) + scroll.value); + break; + case ScrollKind::Page: + SetScrollOffset(direction, GetScrollOffset(direction) + + (direction == Direction::Horizontal + ? GetViewRect().width + : GetViewRect().height) * + scroll.value); + break; + case ScrollKind::Line: + SetScrollOffset(direction, + GetScrollOffset(direction) + kLineHeight * scroll.value); + break; + default: + break; + } } RenderObject* ScrollRenderObject::HitTest(const Point& point) { -- cgit v1.2.3