-
Notifications
You must be signed in to change notification settings - Fork 26
/
ChakraHost.cs
218 lines (176 loc) · 8.65 KB
/
ChakraHost.cs
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Storage;
namespace ChakraBridge
{
public sealed class ChakraHost
{
private readonly JavaScriptNativeFunction SetTimeoutJavaScriptNativeFunction; // Required to keep a reference
private readonly JavaScriptNativeFunction SendToHostJavaScriptNativeFunction; // Required to keep a reference
private JavaScriptSourceContext currentSourceContext = JavaScriptSourceContext.FromIntPtr(IntPtr.Zero);
private readonly JavaScriptRuntime runtime;
private JavaScriptValue promiseCallback;
private readonly JavaScriptContext context;
private Window window;
public ChakraHost()
{
if (Native.JsCreateRuntime(JavaScriptRuntimeAttributes.None, null, out runtime) !=
JavaScriptErrorCode.NoError)
{
throw new Exception("failed to create runtime.");
}
if (Native.JsCreateContext(runtime, out context) != JavaScriptErrorCode.NoError)
throw new Exception("failed to create execution context.");
if (Native.JsSetCurrentContext(context) != JavaScriptErrorCode.NoError)
throw new Exception("failed to set current context.");
// ES6 Promise callback
JavaScriptPromiseContinuationCallback promiseContinuationCallback =
delegate (JavaScriptValue task, IntPtr callbackState)
{
promiseCallback = task;
};
if (Native.JsSetPromiseContinuationCallback(promiseContinuationCallback, IntPtr.Zero) !=
JavaScriptErrorCode.NoError)
throw new Exception("failed to setup callback for ES6 Promise");
// Bind to global object
// setTimeout
SetTimeoutJavaScriptNativeFunction = SetTimeout.SetTimeoutJavaScriptNativeFunction;
DefineHostCallback("setTimeout", SetTimeoutJavaScriptNativeFunction);
SendToHostJavaScriptNativeFunction = CommunicationManager.SendToHostJavaScriptNativeFunction;
DefineHostCallback("sendToHost", SendToHostJavaScriptNativeFunction);
// Projections
if (Native.JsProjectWinRTNamespace("ChakraBridge") != JavaScriptErrorCode.NoError)
throw new Exception("failed to project ChakraBridge namespace.");
this.window = new Window();
ProjectObjectToGlobal(new Console(), "console");
ProjectObjectToGlobal(this.window, "window");
ProjectObjectToGlobal(this.window.navigator, "navigator");
ProjectObjectToGlobal(this.window.document, "document");
// Add references
RunScript(@"XMLHttpRequest = ChakraBridge.XMLHttpRequest;
HTMLCanvasElement = ChakraBridge.HTMLCanvasElementWrapper;
atob = window.atob;
btoa = window.btoa;");
#if DEBUG
// Debug
if (Native.JsStartDebugging() != JavaScriptErrorCode.NoError)
throw new Exception("failed to start debugging.");
#endif
}
public IWindow Window
{
get { return this.window; }
}
public void ProjectNamespace(string namespaceName)
{
if (Native.JsProjectWinRTNamespace(namespaceName) != JavaScriptErrorCode.NoError)
throw new Exception($"failed to project {namespaceName} namespace.");
}
public string RunScript(string script)
{
IntPtr returnValue;
JavaScriptValue result;
if (Native.JsRunScript(script, currentSourceContext++, "", out result) != JavaScriptErrorCode.NoError)
{
// Get error message and clear exception
JavaScriptValue exception;
if (Native.JsGetAndClearException(out exception) != JavaScriptErrorCode.NoError)
throw new Exception("failed to get and clear exception");
JavaScriptPropertyId messageName;
if (Native.JsGetPropertyIdFromName("message",
out messageName) != JavaScriptErrorCode.NoError)
throw new Exception("failed to get error message id");
JavaScriptValue messageValue;
if (Native.JsGetProperty(exception, messageName, out messageValue)
!= JavaScriptErrorCode.NoError)
throw new Exception("failed to get error message");
IntPtr message;
UIntPtr length;
if (Native.JsStringToPointer(messageValue, out message, out length) != JavaScriptErrorCode.NoError)
throw new Exception("failed to convert error message");
return Marshal.PtrToStringUni(message);
}
// Execute promise tasks stored in promiseCallback
while (promiseCallback.IsValid)
{
JavaScriptValue task = promiseCallback;
promiseCallback = JavaScriptValue.Invalid;
JavaScriptValue promiseResult;
Native.JsCallFunction(task, null, 0, out promiseResult);
}
// Convert the return value.
JavaScriptValue stringResult;
UIntPtr stringLength;
if (Native.JsConvertValueToString(result, out stringResult) != JavaScriptErrorCode.NoError)
throw new Exception("failed to convert value to string.");
if (Native.JsStringToPointer(stringResult, out returnValue, out stringLength) !=
JavaScriptErrorCode.NoError)
throw new Exception("failed to convert return value.");
return Marshal.PtrToStringUni(returnValue);
}
public string ProjectObjectToGlobal(object objectToProject, string name)
{
JavaScriptValue value;
if (Native.JsInspectableToObject(objectToProject, out value) != JavaScriptErrorCode.NoError)
return $"failed to project {name} object";
DefineHostProperty(name, value);
return "NoError";
}
public void CallFunction(string name, params object[] parameters)
{
JavaScriptValue globalObject;
Native.JsGetGlobalObject(out globalObject);
JavaScriptPropertyId functionId = JavaScriptPropertyId.FromString(name);
var function = globalObject.GetProperty(functionId);
// Parameters
var javascriptParameters = new List<JavaScriptValue>();
javascriptParameters.Add(globalObject); // this value
foreach (var parameter in parameters)
{
var parameterType = parameter.GetType().Name;
switch (parameterType)
{
case "Int32":
javascriptParameters.Add(JavaScriptValue.FromInt32((int)parameter));
break;
case "Double":
javascriptParameters.Add(JavaScriptValue.FromDouble((double)parameter));
break;
case "Boolean":
javascriptParameters.Add(JavaScriptValue.FromBoolean((bool)parameter));
break;
case "String":
javascriptParameters.Add(JavaScriptValue.FromString((string)parameter));
break;
default:
throw new Exception("Not supported type: " + parameterType);
}
}
// call function
function.CallFunction(javascriptParameters.ToArray());
}
// Private tools
private static void DefineHostCallback(string callbackName, JavaScriptNativeFunction callback)
{
JavaScriptValue globalObject;
Native.JsGetGlobalObject(out globalObject);
JavaScriptPropertyId propertyId = JavaScriptPropertyId.FromString(callbackName);
JavaScriptValue function = JavaScriptValue.CreateFunction(callback, IntPtr.Zero);
globalObject.SetProperty(propertyId, function, true);
uint refCount;
Native.JsAddRef(function, out refCount);
}
private static void DefineHostProperty(string callbackName, JavaScriptValue value)
{
JavaScriptValue globalObject;
Native.JsGetGlobalObject(out globalObject);
JavaScriptPropertyId propertyId = JavaScriptPropertyId.FromString(callbackName);
globalObject.SetProperty(propertyId, value, true);
uint refCount;
Native.JsAddRef(value, out refCount);
}
}
}