ModelIndex.h 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. Model const* model() const { return m_model; }
  27. Variant data(ModelRole = ModelRole::Display) const;
  28. ModelIndex sibling(int row, int column) const;
  29. ModelIndex sibling_at_column(int column) const;
  30. private:
  31. ModelIndex(Model const& model, int row, int column, void* internal_data)
  32. : m_model(&model)
  33. , m_row(row)
  34. , m_column(column)
  35. , m_internal_data(internal_data)
  36. {
  37. }
  38. Model const* m_model { nullptr };
  39. int m_row { -1 };
  40. int m_column { -1 };
  41. void* m_internal_data { nullptr };
  42. };
  43. }
  44. namespace AK {
  45. template<>
  46. struct Formatter<GUI::ModelIndex> : Formatter<FormatString> {
  47. ErrorOr<void> format(FormatBuilder& builder, GUI::ModelIndex const& value)
  48. {
  49. if (value.internal_data())
  50. return Formatter<FormatString>::format(builder, "ModelIndex({},{},{})"sv, value.row(), value.column(), value.internal_data());
  51. return Formatter<FormatString>::format(builder, "ModelIndex({},{})"sv, value.row(), value.column());
  52. }
  53. };
  54. template<>
  55. struct Traits<GUI::ModelIndex> : public GenericTraits<GUI::ModelIndex> {
  56. static unsigned hash(const GUI::ModelIndex& index)
  57. {
  58. return pair_int_hash(pair_int_hash(index.row(), index.column()), reinterpret_cast<FlatPtr>(index.internal_data()));
  59. }
  60. };
  61. }