ModelEditingDelegate.h 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <LibGUI/Model.h>
  8. #include <LibGUI/TextBox.h>
  9. #include <LibGUI/Widget.h>
  10. namespace GUI {
  11. class ModelEditingDelegate {
  12. public:
  13. enum SelectionBehavior {
  14. DoNotSelect,
  15. SelectAll,
  16. };
  17. virtual ~ModelEditingDelegate() { }
  18. void bind(Model& model, const ModelIndex& index)
  19. {
  20. if (m_model.ptr() == &model && m_index == index)
  21. return;
  22. m_model = model;
  23. m_index = index;
  24. m_widget = create_widget();
  25. }
  26. Widget* widget() { return m_widget; }
  27. const Widget* widget() const { return m_widget; }
  28. Function<void()> on_commit;
  29. Function<void()> on_rollback;
  30. Function<void()> on_change;
  31. virtual Variant value() const = 0;
  32. virtual void set_value(Variant const&, SelectionBehavior selection_behavior = SelectionBehavior::SelectAll) = 0;
  33. virtual void will_begin_editing() { }
  34. protected:
  35. ModelEditingDelegate() { }
  36. virtual RefPtr<Widget> create_widget() = 0;
  37. void commit()
  38. {
  39. if (on_commit)
  40. on_commit();
  41. }
  42. void rollback()
  43. {
  44. if (on_rollback)
  45. on_rollback();
  46. }
  47. void change()
  48. {
  49. if (on_change)
  50. on_change();
  51. }
  52. const ModelIndex& index() const { return m_index; }
  53. private:
  54. RefPtr<Model> m_model;
  55. ModelIndex m_index;
  56. RefPtr<Widget> m_widget;
  57. };
  58. class StringModelEditingDelegate : public ModelEditingDelegate {
  59. public:
  60. StringModelEditingDelegate() { }
  61. virtual ~StringModelEditingDelegate() override { }
  62. virtual RefPtr<Widget> create_widget() override
  63. {
  64. auto textbox = TextBox::construct();
  65. textbox->set_frame_shape(Gfx::FrameShape::NoFrame);
  66. textbox->on_return_pressed = [this] {
  67. commit();
  68. };
  69. textbox->on_escape_pressed = [this] {
  70. rollback();
  71. };
  72. textbox->on_change = [this] {
  73. change();
  74. };
  75. return textbox;
  76. }
  77. virtual Variant value() const override { return static_cast<const TextBox*>(widget())->text(); }
  78. virtual void set_value(Variant const& value, SelectionBehavior selection_behavior) override
  79. {
  80. auto& textbox = static_cast<TextBox&>(*widget());
  81. textbox.set_text(value.to_string());
  82. if (selection_behavior == SelectionBehavior::SelectAll)
  83. textbox.select_all();
  84. }
  85. };
  86. }