GModel.h 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. #pragma once
  2. #include <AK/String.h>
  3. #include <AK/Badge.h>
  4. #include <AK/Function.h>
  5. #include <AK/HashTable.h>
  6. #include <AK/RefCounted.h>
  7. #include <LibGUI/GModelIndex.h>
  8. #include <LibGUI/GVariant.h>
  9. #include <LibDraw/TextAlignment.h>
  10. class Font;
  11. class GAbstractView;
  12. enum class GSortOrder {
  13. None,
  14. Ascending,
  15. Descending
  16. };
  17. class GModel : public RefCounted<GModel> {
  18. public:
  19. struct ColumnMetadata {
  20. int preferred_width { 0 };
  21. TextAlignment text_alignment { TextAlignment::CenterLeft };
  22. const Font* font { nullptr };
  23. enum class Sortable { False, True };
  24. Sortable sortable { Sortable::True };
  25. };
  26. enum class Role {
  27. Display,
  28. Sort,
  29. Custom,
  30. ForegroundColor,
  31. BackgroundColor,
  32. Icon
  33. };
  34. virtual ~GModel();
  35. virtual int row_count(const GModelIndex& = GModelIndex()) const = 0;
  36. virtual int column_count(const GModelIndex& = GModelIndex()) const = 0;
  37. virtual String row_name(int) const { return {}; }
  38. virtual String column_name(int) const { return {}; }
  39. virtual ColumnMetadata column_metadata(int) const { return {}; }
  40. virtual GVariant data(const GModelIndex&, Role = Role::Display) const = 0;
  41. virtual void update() = 0;
  42. virtual GModelIndex parent_index(const GModelIndex&) const { return {}; }
  43. virtual GModelIndex index(int row, int column = 0, const GModelIndex& = GModelIndex()) const { return create_index(row, column); }
  44. virtual GModelIndex sibling(int row, int column, const GModelIndex& parent) const;
  45. virtual bool is_editable(const GModelIndex&) const { return false; }
  46. virtual void set_data(const GModelIndex&, const GVariant&) {}
  47. bool is_valid(const GModelIndex& index) const
  48. {
  49. return index.row() >= 0 && index.row() < row_count() && index.column() >= 0 && index.column() < column_count();
  50. }
  51. virtual int key_column() const { return -1; }
  52. virtual GSortOrder sort_order() const { return GSortOrder::None; }
  53. virtual void set_key_column_and_sort_order(int, GSortOrder) {}
  54. void register_view(Badge<GAbstractView>, GAbstractView&);
  55. void unregister_view(Badge<GAbstractView>, GAbstractView&);
  56. Function<void()> on_update;
  57. Function<void(const GModelIndex&)> on_selection_changed;
  58. protected:
  59. GModel();
  60. void for_each_view(Function<void(GAbstractView&)>);
  61. void did_update();
  62. GModelIndex create_index(int row, int column, const void* data = nullptr) const;
  63. private:
  64. HashTable<GAbstractView*> m_views;
  65. };
  66. inline GModelIndex GModelIndex::parent() const
  67. {
  68. return m_model ? m_model->parent_index(*this) : GModelIndex();
  69. }