#include "config.h"
#include "ScriptRunner.h"
#include "CachedScript.h"
#include "Element.h"
#include "PendingScript.h"
#include "ScriptElement.h"
namespace WebCore {
ScriptRunner::ScriptRunner(Document& document)
: m_document(document)
, m_timer(*this, &ScriptRunner::timerFired)
{
}
ScriptRunner::~ScriptRunner()
{
for (size_t i = 0; i < m_scriptsToExecuteSoon.size(); ++i)
m_document.decrementLoadEventDelayCount();
for (size_t i = 0; i < m_scriptsToExecuteInOrder.size(); ++i)
m_document.decrementLoadEventDelayCount();
for (unsigned i = 0; i < m_pendingAsyncScripts.size(); ++i)
m_document.decrementLoadEventDelayCount();
}
void ScriptRunner::queueScriptForExecution(ScriptElement* scriptElement, CachedResourceHandle<CachedScript> cachedScript, ExecutionType executionType)
{
ASSERT(scriptElement);
ASSERT(cachedScript.get());
Element& element = scriptElement->element();
ASSERT(element.inDocument());
m_document.incrementLoadEventDelayCount();
switch (executionType) {
case ASYNC_EXECUTION:
m_pendingAsyncScripts.add(scriptElement, PendingScript(&element, cachedScript.get()));
break;
case IN_ORDER_EXECUTION:
m_scriptsToExecuteInOrder.append(PendingScript(&element, cachedScript.get()));
break;
}
}
void ScriptRunner::suspend()
{
m_timer.stop();
}
void ScriptRunner::resume()
{
if (hasPendingScripts())
m_timer.startOneShot(0);
}
void ScriptRunner::notifyScriptReady(ScriptElement* scriptElement, ExecutionType executionType)
{
switch (executionType) {
case ASYNC_EXECUTION:
ASSERT(m_pendingAsyncScripts.contains(scriptElement));
m_scriptsToExecuteSoon.append(m_pendingAsyncScripts.take(scriptElement));
break;
case IN_ORDER_EXECUTION:
ASSERT(!m_scriptsToExecuteInOrder.isEmpty());
break;
}
m_timer.startOneShot(0);
}
void ScriptRunner::timerFired()
{
Ref<Document> protect(m_document);
Vector<PendingScript> scripts;
scripts.swap(m_scriptsToExecuteSoon);
size_t numInOrderScriptsToExecute = 0;
for (; numInOrderScriptsToExecute < m_scriptsToExecuteInOrder.size() && m_scriptsToExecuteInOrder[numInOrderScriptsToExecute].cachedScript()->isLoaded(); ++numInOrderScriptsToExecute)
scripts.append(m_scriptsToExecuteInOrder[numInOrderScriptsToExecute]);
if (numInOrderScriptsToExecute)
m_scriptsToExecuteInOrder.remove(0, numInOrderScriptsToExecute);
for (auto& script : scripts) {
CachedScript* cachedScript = script.cachedScript();
RefPtr<Element> element = script.releaseElementAndClear();
ASSERT(element);
if (!element)
continue;
toScriptElementIfPossible(element.get())->execute(cachedScript);
m_document.decrementLoadEventDelayCount();
}
}
}