forked from BabylonJS/JsRuntimeHost
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAppRuntime_Chakra.cpp
More file actions
81 lines (70 loc) · 2.61 KB
/
Copy pathAppRuntime_Chakra.cpp
File metadata and controls
81 lines (70 loc) · 2.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#include "AppRuntime.h"
#include <napi/env.h>
#define USE_EDGEMODE_JSRT
#include <jsrt.h>
#include <gsl/gsl>
#include <cassert>
#include <sstream>
namespace Babylon
{
namespace
{
void ThrowIfFailed(JsErrorCode errorCode)
{
if (errorCode != JsErrorCode::JsNoError)
{
std::ostringstream ss;
ss << "Chakra function failed with error code (" << static_cast<int>(errorCode) << ")";
throw std::runtime_error{ss.str()};
}
}
}
void AppRuntime::RunEnvironmentTier(const char*)
{
using DispatchFunction = std::function<void(std::function<void()>)>;
DispatchFunction dispatchFunction{
[this](std::function<void()> action) {
Dispatch([action = std::move(action)](Napi::Env) {
action();
});
}};
JsRuntimeHandle jsRuntime;
ThrowIfFailed(JsCreateRuntime(JsRuntimeAttributeNone, nullptr, &jsRuntime));
JsContextRef context;
ThrowIfFailed(JsCreateContext(jsRuntime, &context));
ThrowIfFailed(JsSetCurrentContext(context));
ThrowIfFailed(JsSetPromiseContinuationCallback(
[](JsValueRef task, void* callbackState) {
ThrowIfFailed(JsAddRef(task, nullptr));
auto* dispatch = reinterpret_cast<DispatchFunction*>(callbackState);
dispatch->operator()([task]() {
JsValueRef undefined;
ThrowIfFailed(JsGetUndefinedValue(&undefined));
ThrowIfFailed(JsCallFunction(task, &undefined, 1, nullptr));
ThrowIfFailed(JsRelease(task, nullptr));
});
},
&dispatchFunction));
ThrowIfFailed(JsProjectWinRTNamespace(L"Windows"));
if (m_options.EnableDebugger)
{
auto result = JsStartDebugging();
if (result != JsErrorCode::JsNoError)
{
OutputDebugStringW(L"Failed to initialize JavaScript debugging support.\n");
}
}
Napi::Env env = Napi::Attach();
Run(env);
ThrowIfFailed(JsSetCurrentContext(JS_INVALID_REFERENCE));
ThrowIfFailed(JsDisposeRuntime(jsRuntime));
// Detach must come after JsDisposeRuntime since it triggers finalizers which require env.
Napi::Detach(env);
}
void AppRuntime::DrainMicrotasks(Napi::Env)
{
// Chakra drains promise continuations through its
// JsSetPromiseContinuationCallback hook (see RunEnvironmentTier).
// No explicit pump needed here.
}
}