ModelSelection.cpp 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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_all_matching(Function<bool(ModelIndex const&)> filter)
  11. {
  12. if (m_indices.remove_all_matching([&](ModelIndex const& index) { return filter(index); }))
  13. notify_selection_changed();
  14. }
  15. void ModelSelection::set(ModelIndex const& index)
  16. {
  17. VERIFY(index.is_valid());
  18. if (m_indices.size() == 1 && m_indices.contains(index))
  19. return;
  20. m_indices.clear();
  21. m_indices.set(index);
  22. notify_selection_changed();
  23. }
  24. void ModelSelection::add(ModelIndex const& index)
  25. {
  26. VERIFY(index.is_valid());
  27. if (m_indices.set(index) == AK::HashSetResult::InsertedNewEntry)
  28. notify_selection_changed();
  29. }
  30. void ModelSelection::add_all(Vector<ModelIndex> const& indices)
  31. {
  32. {
  33. TemporaryChange notify_change { m_disable_notify, true };
  34. for (auto& index : indices)
  35. add(index);
  36. }
  37. if (m_notify_pending)
  38. notify_selection_changed();
  39. }
  40. void ModelSelection::toggle(ModelIndex const& index)
  41. {
  42. VERIFY(index.is_valid());
  43. if (m_indices.contains(index))
  44. m_indices.remove(index);
  45. else
  46. m_indices.set(index);
  47. notify_selection_changed();
  48. }
  49. bool ModelSelection::remove(ModelIndex const& index)
  50. {
  51. VERIFY(index.is_valid());
  52. if (!m_indices.contains(index))
  53. return false;
  54. m_indices.remove(index);
  55. notify_selection_changed();
  56. return true;
  57. }
  58. void ModelSelection::clear()
  59. {
  60. if (m_indices.is_empty())
  61. return;
  62. m_indices.clear();
  63. notify_selection_changed();
  64. }
  65. void ModelSelection::notify_selection_changed()
  66. {
  67. if (!m_disable_notify) {
  68. m_view.notify_selection_changed({});
  69. m_notify_pending = false;
  70. } else {
  71. m_notify_pending = true;
  72. }
  73. }
  74. }