ModelIndex.h 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. /*
  2. * Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <AK/Format.h>
  8. #include <AK/Traits.h>
  9. #include <LibGUI/Forward.h>
  10. #include <LibGUI/ModelRole.h>
  11. namespace GUI {
  12. class ModelIndex {
  13. friend class Model;
  14. public:
  15. ModelIndex() = default;
  16. bool is_valid() const { return m_model && m_row != -1 && m_column != -1; }
  17. int row() const { return m_row; }
  18. int column() const { return m_column; }
  19. void* internal_data() const { return m_internal_data; }
  20. ModelIndex parent() const;
  21. bool is_parent_of(ModelIndex const&) const;
  22. bool operator==(ModelIndex const& other) const
  23. {
  24. return m_model == other.m_model && m_row == other.m_row && m_column == other.m_column && m_internal_data == other.m_internal_data;
  25. }
  26. bool operator!=(ModelIndex const& other) const
  27. {
  28. return !(*this == other);
  29. }
  30. Model const* model() const { return m_model; }
  31. Variant data(ModelRole = ModelRole::Display) const;
  32. ModelIndex sibling(int row, int column) const;
  33. ModelIndex sibling_at_column(int column) const;
  34. private:
  35. ModelIndex(Model const& model, int row, int column, void* internal_data)
  36. : m_model(&model)
  37. , m_row(row)
  38. , m_column(column)
  39. , m_internal_data(internal_data)
  40. {
  41. }
  42. Model const* m_model { nullptr };
  43. int m_row { -1 };
  44. int m_column { -1 };
  45. void* m_internal_data { nullptr };
  46. };
  47. }
  48. namespace AK {
  49. template<>
  50. struct Formatter<GUI::ModelIndex> : Formatter<FormatString> {
  51. ErrorOr<void> format(FormatBuilder& builder, GUI::ModelIndex const& value)
  52. {
  53. if (value.internal_data())
  54. return Formatter<FormatString>::format(builder, "ModelIndex({},{},{})", value.row(), value.column(), value.internal_data());
  55. return Formatter<FormatString>::format(builder, "ModelIndex({},{})", value.row(), value.column());
  56. }
  57. };
  58. template<>
  59. struct Traits<GUI::ModelIndex> : public GenericTraits<GUI::ModelIndex> {
  60. static unsigned hash(const GUI::ModelIndex& index)
  61. {
  62. return pair_int_hash(pair_int_hash(index.row(), index.column()), reinterpret_cast<FlatPtr>(index.internal_data()));
  63. }
  64. };
  65. }