ModelSelection.cpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibGUI/AbstractView.h>
  7. #include <LibGUI/Model.h>
  8. #include <LibGUI/ModelSelection.h>
  9. namespace GUI {
  10. void ModelSelection::remove_matching(Function<bool(const ModelIndex&)> filter)
  11. {
  12. Vector<ModelIndex> to_remove;
  13. for (auto& index : m_indices) {
  14. if (filter(index))
  15. to_remove.append(index);
  16. }
  17. if (!to_remove.is_empty()) {
  18. for (auto& index : to_remove)
  19. m_indices.remove(index);
  20. notify_selection_changed();
  21. }
  22. }
  23. void ModelSelection::set(const ModelIndex& index)
  24. {
  25. VERIFY(index.is_valid());
  26. if (m_indices.size() == 1 && m_indices.contains(index))
  27. return;
  28. m_indices.clear();
  29. m_indices.set(index);
  30. notify_selection_changed();
  31. }
  32. void ModelSelection::add(const ModelIndex& index)
  33. {
  34. VERIFY(index.is_valid());
  35. if (m_indices.contains(index))
  36. return;
  37. m_indices.set(index);
  38. notify_selection_changed();
  39. }
  40. void ModelSelection::add_all(const Vector<ModelIndex>& indices)
  41. {
  42. {
  43. TemporaryChange notify_change { m_disable_notify, true };
  44. for (auto& index : indices)
  45. add(index);
  46. }
  47. if (m_notify_pending)
  48. notify_selection_changed();
  49. }
  50. void ModelSelection::toggle(const ModelIndex& index)
  51. {
  52. VERIFY(index.is_valid());
  53. if (m_indices.contains(index))
  54. m_indices.remove(index);
  55. else
  56. m_indices.set(index);
  57. notify_selection_changed();
  58. }
  59. bool ModelSelection::remove(const ModelIndex& index)
  60. {
  61. VERIFY(index.is_valid());
  62. if (!m_indices.contains(index))
  63. return false;
  64. m_indices.remove(index);
  65. notify_selection_changed();
  66. return true;
  67. }
  68. void ModelSelection::clear()
  69. {
  70. if (m_indices.is_empty())
  71. return;
  72. m_indices.clear();
  73. notify_selection_changed();
  74. }
  75. void ModelSelection::notify_selection_changed()
  76. {
  77. if (!m_disable_notify) {
  78. m_view.notify_selection_changed({});
  79. m_notify_pending = false;
  80. } else {
  81. m_notify_pending = true;
  82. }
  83. }
  84. }