TaskQueue.cpp 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /*
  2. * Copyright (c) 2021, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibWeb/HTML/EventLoop/EventLoop.h>
  7. #include <LibWeb/HTML/EventLoop/TaskQueue.h>
  8. namespace Web::HTML {
  9. TaskQueue::TaskQueue(HTML::EventLoop& event_loop)
  10. : m_event_loop(event_loop)
  11. {
  12. }
  13. TaskQueue::~TaskQueue() = default;
  14. void TaskQueue::add(NonnullOwnPtr<Task> task)
  15. {
  16. m_tasks.append(move(task));
  17. m_event_loop.schedule();
  18. }
  19. OwnPtr<Task> TaskQueue::take_first_runnable()
  20. {
  21. if (m_event_loop.execution_paused())
  22. return nullptr;
  23. for (size_t i = 0; i < m_tasks.size(); ++i) {
  24. if (m_tasks[i]->is_runnable())
  25. return m_tasks.take(i);
  26. }
  27. return nullptr;
  28. }
  29. bool TaskQueue::has_runnable_tasks() const
  30. {
  31. if (m_event_loop.execution_paused())
  32. return false;
  33. for (auto& task : m_tasks) {
  34. if (task->is_runnable())
  35. return true;
  36. }
  37. return false;
  38. }
  39. void TaskQueue::remove_tasks_matching(Function<bool(HTML::Task const&)> filter)
  40. {
  41. m_tasks.remove_all_matching([&](auto& task) {
  42. return filter(*task);
  43. });
  44. }
  45. ErrorOr<Vector<NonnullOwnPtr<Task>>> TaskQueue::take_tasks_matching(Function<bool(HTML::Task const&)> filter)
  46. {
  47. Vector<NonnullOwnPtr<Task>> matching_tasks;
  48. for (size_t i = 0; i < m_tasks.size();) {
  49. auto& task = m_tasks.at(i);
  50. if (filter(*task)) {
  51. TRY(matching_tasks.try_append(move(task)));
  52. m_tasks.remove(i);
  53. } else {
  54. ++i;
  55. }
  56. }
  57. return matching_tasks;
  58. }
  59. Task const* TaskQueue::last_added_task() const
  60. {
  61. if (m_tasks.is_empty())
  62. return nullptr;
  63. return m_tasks.last();
  64. }
  65. }