ModelSelection.cpp 2.1 KB

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