ModelIndex.h 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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(const ModelIndex&) const;
  22. bool operator==(const ModelIndex& 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!=(const ModelIndex& other) const
  27. {
  28. return !(*this == other);
  29. }
  30. const Model* 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(const Model& 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. const Model* 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. void format(FormatBuilder& builder, const GUI::ModelIndex& value)
  52. {
  53. if (value.internal_data())
  54. return Formatter<FormatString>::format(builder, "ModelIndex({},{},{})", value.row(), value.column(), value.internal_data());
  55. else
  56. return Formatter<FormatString>::format(builder, "ModelIndex({},{})", value.row(), value.column());
  57. }
  58. };
  59. template<>
  60. struct Traits<GUI::ModelIndex> : public GenericTraits<GUI::ModelIndex> {
  61. static unsigned hash(const GUI::ModelIndex& index)
  62. {
  63. return pair_int_hash(pair_int_hash(index.row(), index.column()), reinterpret_cast<FlatPtr>(index.internal_data()));
  64. }
  65. };
  66. }