Task.cpp 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /*
  2. * Copyright (c) 2021-2024, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/IDAllocator.h>
  7. #include <LibWeb/DOM/Document.h>
  8. #include <LibWeb/HTML/EventLoop/Task.h>
  9. namespace Web::HTML {
  10. JS_DEFINE_ALLOCATOR(Task);
  11. static IDAllocator s_unique_task_source_allocator { static_cast<int>(Task::Source::UniqueTaskSourceStart) };
  12. static IDAllocator s_task_id_allocator;
  13. JS::NonnullGCPtr<Task> Task::create(JS::VM& vm, Source source, JS::GCPtr<DOM::Document const> document, JS::NonnullGCPtr<JS::HeapFunction<void()>> steps)
  14. {
  15. return vm.heap().allocate_without_realm<Task>(source, document, move(steps));
  16. }
  17. Task::Task(Source source, JS::GCPtr<DOM::Document const> document, JS::NonnullGCPtr<JS::HeapFunction<void()>> steps)
  18. : m_id(s_task_id_allocator.allocate())
  19. , m_source(source)
  20. , m_steps(steps)
  21. , m_document(document)
  22. {
  23. }
  24. Task::~Task() = default;
  25. void Task::finalize()
  26. {
  27. s_unique_task_source_allocator.deallocate(m_id);
  28. }
  29. void Task::visit_edges(Visitor& visitor)
  30. {
  31. Base::visit_edges(visitor);
  32. visitor.visit(m_steps);
  33. visitor.visit(m_document);
  34. }
  35. void Task::execute()
  36. {
  37. m_steps->function()();
  38. }
  39. // https://html.spec.whatwg.org/#concept-task-runnable
  40. bool Task::is_runnable() const
  41. {
  42. // A task is runnable if its document is either null or fully active.
  43. return !m_document.ptr() || m_document->is_fully_active();
  44. }
  45. DOM::Document const* Task::document() const
  46. {
  47. return m_document.ptr();
  48. }
  49. UniqueTaskSource::UniqueTaskSource()
  50. : source(static_cast<Task::Source>(s_unique_task_source_allocator.allocate()))
  51. {
  52. }
  53. UniqueTaskSource::~UniqueTaskSource()
  54. {
  55. s_unique_task_source_allocator.deallocate(static_cast<int>(source));
  56. }
  57. }