PersistentModelIndex.h 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. /*
  2. * Copyright (c) 2021, sin-ack <sin-ack@protonmail.com>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <AK/RefCounted.h>
  8. #include <AK/WeakPtr.h>
  9. #include <LibGUI/Model.h>
  10. #include <LibGUI/ModelIndex.h>
  11. namespace GUI {
  12. /// A PersistentHandle is an internal data structure used to keep track of the
  13. /// target of multiple PersistentModelIndex instances.
  14. class PersistentHandle : public Weakable<PersistentHandle> {
  15. friend Model;
  16. friend PersistentModelIndex;
  17. friend AK::Traits<GUI::PersistentModelIndex>;
  18. PersistentHandle(ModelIndex const& index)
  19. : m_index(index)
  20. {
  21. }
  22. ModelIndex m_index;
  23. };
  24. class PersistentModelIndex {
  25. public:
  26. PersistentModelIndex() { }
  27. PersistentModelIndex(ModelIndex const&);
  28. PersistentModelIndex(PersistentModelIndex const&) = default;
  29. PersistentModelIndex(PersistentModelIndex&&) = default;
  30. PersistentModelIndex& operator=(PersistentModelIndex const&) = default;
  31. PersistentModelIndex& operator=(PersistentModelIndex&&) = default;
  32. bool is_valid() const { return has_valid_handle() && m_handle->m_index.is_valid(); }
  33. bool has_valid_handle() const { return !m_handle.is_null(); }
  34. int row() const;
  35. int column() const;
  36. PersistentModelIndex parent() const;
  37. PersistentModelIndex sibling_at_column(int column) const;
  38. Variant data(ModelRole = ModelRole::Display) const;
  39. void* internal_data() const
  40. {
  41. if (has_valid_handle())
  42. return m_handle->m_index.internal_data();
  43. else
  44. return nullptr;
  45. }
  46. operator ModelIndex() const;
  47. bool operator==(PersistentModelIndex const&) const;
  48. bool operator!=(PersistentModelIndex const&) const;
  49. bool operator==(ModelIndex const&) const;
  50. bool operator!=(ModelIndex const&) const;
  51. private:
  52. friend AK::Traits<GUI::PersistentModelIndex>;
  53. WeakPtr<PersistentHandle> m_handle;
  54. };
  55. }
  56. namespace AK {
  57. template<>
  58. struct Formatter<GUI::PersistentModelIndex> : Formatter<FormatString> {
  59. void format(FormatBuilder& builder, const GUI::PersistentModelIndex& value)
  60. {
  61. return Formatter<FormatString>::format(builder, "PersistentModelIndex({},{},{})", value.row(), value.column(), value.internal_data());
  62. }
  63. };
  64. template<>
  65. struct Traits<GUI::PersistentModelIndex> : public GenericTraits<GUI::PersistentModelIndex> {
  66. static unsigned hash(const GUI::PersistentModelIndex& index)
  67. {
  68. if (index.has_valid_handle())
  69. return Traits<GUI::ModelIndex>::hash(index.m_handle->m_index);
  70. else
  71. return 0;
  72. }
  73. };
  74. }