-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathAsyncronousEngine.cs
378 lines (350 loc) · 13.3 KB
/
AsyncronousEngine.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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
using System.Diagnostics;
using System.Linq.Expressions;
using System.Runtime.InteropServices;
using System.Threading;
//1using System.Timers;
using DynamicSugar;
using Jint;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using Jint.Native;
namespace Jint.Ex
{
public class AsyncronousEngine
{
private readonly CallBackEventQueue _eventQueue = new CallBackEventQueue();
private Thread _mainThread = null;
private int _mainThreadRunningSemaphore = 0;
private bool _runBackgroundThread = true;
private Jint.Engine _engine = null;
/// <summary>
/// Reference the assembly that embed the JavaScript scripts.
/// </summary>
public List<Assembly> EmbedScriptAssemblies = new List<Assembly>();
/// <summary>
/// Allocate a Jint instance and registered all the standard methods
/// setTimeout, clearTimeout, setInterval, clearInterval, print
/// </summary>
/// <returns></returns>
private Engine AllocateNewJintInstance()
{
var e = new Engine(c => c.AllowClr());
e.SetValue("setTimeout" , new Func<Func<Jint.Native.JsValue, Jint.Native.JsValue[], Jint.Native.JsValue>, double, int>(__setTimeout__));
e.SetValue("clearTimeout" , new Action<int>(__clearTimeout__));
e.SetValue("setInterval" , new Func<Func<Jint.Native.JsValue, Jint.Native.JsValue[], Jint.Native.JsValue>, double, int>(__setInterval__));
e.SetValue("clearInterval", new Action<int>(__clearInterval__));
e.SetValue("print", new Action<object>(Print)); // << TODO: Parameterize the method
return e;
}
/// <summary>
///
/// </summary>
public void Reset()
{
this.EmbedScriptAssemblies.Clear();
this.Stop();
_engine = null;
}
/// <summary>
/// The instance of Jint
/// </summary>
public Jint.Engine Engine
{
get
{
if (this._engine == null)
this._engine = AllocateNewJintInstance();
return this._engine;
}
}
/// <summary>
///
/// </summary>
/// <param name="s"></param>
private static void Print(object s)
{
if (s == null)
s = "null";
Console.WriteLine(s.ToString());
}
/// <summary>
/// Load a file from the file system or as an embed resource
/// </summary>
/// <param name="name"></param>
/// <param name="source"></param>
public void LoadScript(string name, StringBuilder source)
{
if (System.IO.File.Exists(name))
source.Append(System.IO.File.ReadAllText(name)).AppendLine();
else
{
var text = DS.Resources.GetTextResource(name, this.EmbedScriptAssemblies);
source.Append(text).AppendLine();
}
}
/// <summary>
/// Load a file from the file system or as an embed resource
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public string LoadScript(string name)
{
var source = new StringBuilder();
LoadScript(name, source);
return source.ToString();
}
/// <summary>
/// Request the execution of a JavaScript callback function. This method should be called by
/// C# custom object that want to implement asynchronous api.
/// </summary>
/// <param name="callBackFunction"></param>
/// <param name="parameters"></param>
public void RequestCallbackExecution(Func<Jint.Native.JsValue, Jint.Native.JsValue[], Jint.Native.JsValue> callBackFunction, List<JsValue> parameters)
{
this._eventQueue.Enqueue(new CallBackEvent(callBackFunction, parameters));
}
/// <summary>
/// Execute a JavaScript callback function
/// </summary>
/// <param name="callBackFunction"></param>
/// <param name="parameters"></param>
/// <returns></returns>
private JsValue ExecuteCallBack(Func<Jint.Native.JsValue, Jint.Native.JsValue[], Jint.Native.JsValue> callBackFunction, List<JsValue> parameters = null)
{
if(parameters == null)
parameters = new List<JsValue>();
JsValue r = callBackFunction.Invoke( // Call the callback function
JsValue.Undefined, // Pass this as undefined
parameters.ToArray() // Pass the parameter data
);
return r;
}
/// <summary>
///
/// </summary>
/// <param name="name"></param>
/// <param name="obj"></param>
/// <returns></returns>
public void SetValue(string name, Object obj)
{
this.Engine.SetValue(name, obj);
}
/// <summary>
/// Execute the JavaScrip source in a blocking way
/// </summary>
/// <param name="source"></param>
/// <returns></returns>
public JsValue Execute(string source)
{
var jsValue = this.Engine.Execute(source).GetCompletionValue();
return jsValue;
}
/// <summary>
/// Background thread dedicated to execute the MainScript
/// </summary>
private void __BackgroundThread()
{
const int sleepTime = 32;
while (this._runBackgroundThread)
{
#if !__IOS__ // In debug mode this slow down the iPhone simulator to much
Debug.WriteLine(string.Format("_runBackgroundThread:{0} Queue:{1}", Environment.TickCount, _eventQueue.Count));
#endif
if (_eventQueue.Count > 0)
{
// Execute first all events with no delay
var tmpQ = this._eventQueue.GetEventsWithNoDelay();
while(tmpQ.Count > 0)
{
this.ExecuteEvent(tmpQ.Peek(), tmpQ);
}
// Deal with timer event now
Thread.Sleep(sleepTime); // Sleep minimal time
tmpQ = this._eventQueue.CloneEventWithDelay();
foreach(var e in tmpQ)
{
if (e.ReadyForExecution(sleepTime))
{
this.ExecuteEvent(e, null);
}
}
this._eventQueue.RemoveDisabledEvents();
}
else
Thread.Sleep(sleepTime);
}
Interlocked.Decrement(ref _mainThreadRunningSemaphore);
}
private void ExecuteEvent(CallBackEvent c, CallBackEventQueue tmpQ)
{
if (c.Enabled)
{
c.Enabled = false;
switch (c.Type)
{
case CallBackType.ClearQueue:
this._eventQueue.Clear();
break;
case CallBackType.ScriptExecution:
this.Execute(c.Source);
break;
case CallBackType.UserCallback:
this.ExecuteCallBack(c.Function, c.Parameters);
break;
case CallBackType.TimeOut:
this.ExecuteCallBack(c.Function);
break;
case CallBackType.Interval:
c.Enabled = true;
this.ExecuteCallBack(c.Function);
break;
}
}
this._eventQueue.RemoveTopBecauseProcessed(c, true);
if (tmpQ != null)
tmpQ.RemoveTopBecauseProcessed(c, false);
}
/// <summary>
/// Return true if the main thread is running (thread safe)
/// </summary>
private bool IsMainThreadRunning
{
get { return this._mainThreadRunningSemaphore > 0; }
}
/// <summary>
/// Clear the event queue
/// </summary>
public void RequestClearQueue()
{
this._eventQueue.Enqueue(new CallBackEvent(CallBackType.ClearQueue));
}
/// <summary>
/// Wait until the event queue is empty
/// </summary>
public void Wait()
{
while (this._eventQueue.Count > 0)
{
Thread.Sleep(100);
}
}
/// <summary>
/// Stop the event loop
/// </summary>
public void Stop(Action sleepMethod = null)
{
if (this._mainThread != null)
{
this._runBackgroundThread = false;
while (this._mainThread.IsAlive)
{
if (sleepMethod == null)
Thread.Sleep(100);
else
sleepMethod();
}
_mainThread = null;
}
}
/// <summary>
/// Kill the event loop
/// </summary>
public void Kill()
{
if (this._mainThread != null)
{
this._runBackgroundThread = false;
this._mainThread.Abort();
this._mainThread = null;
Thread.Sleep(100);
}
}
/// <summary>
/// Request the execution of one javaScript script file by the event loop.
/// The method returns right away.
/// Start the AsyncronousEngine if needed.
/// </summary>
/// <param name="fileName">The filename or resource name to load and execute</param>
/// <param name="block">If true after the execution, block until the event queue is empty</param>
public bool RequestFileExecution(string fileName, bool block = false)
{
var source = new StringBuilder();
this.LoadScript(fileName, source);
return this.RequestScriptExecution(source.ToString(), block);
}
/// <summary>
/// Request the execution of one javaScript source by the event loop.
/// The method returns right away.
/// Start the AsyncronousEngine if needed.
/// </summary>
/// <param name="fileName">The filename or resource name to load and execute</param>
/// <param name="block">If true after the execution, block until the event queue is empty</param>
public bool RequestScriptExecution(string source, bool block = false)
{
if (!this.IsMainThreadRunning)
this.Start();
this._eventQueue.RequestScriptExecution(source.ToString());
if (block)
{
this.Wait();
this.Stop();
}
return true;
}
/// <summary>
/// Start the event loop
/// </summary>
/// <returns></returns>
public bool Start()
{
if (this.IsMainThreadRunning)
{
return false;
}
else
{
Interlocked.Increment(ref _mainThreadRunningSemaphore);
this._mainThread = new Thread(new ThreadStart(__BackgroundThread)) { Name = "Jint.Ex.BackgroundExecutionThread" };
this._runBackgroundThread = true;
this._mainThread.Start();
return true;
}
}
#region JavaScriptFunction
/// <summary>
/// https://developer.mozilla.org/en-US/docs/Web/API/Window.setInterval
/// </summary>
/// <param name="callBackFunction"></param>
/// <param name="delay"></param>
/// <returns></returns>
public int __setInterval__(Func<Jint.Native.JsValue, Jint.Native.JsValue[], Jint.Native.JsValue> callBackFunction, double delay)
{
return this._eventQueue.Enqueue(new CallBackEvent(callBackFunction, delay, CallBackType.Interval)).Id;
}
/// <summary>
/// https://developer.mozilla.org/en-US/docs/Web/API/Window.setTimeout
/// </summary>
/// <param name="callBackFunction"></param>
/// <param name="delay"></param>
/// <returns></returns>
private int __setTimeout__(Func<Jint.Native.JsValue, Jint.Native.JsValue[], Jint.Native.JsValue> callBackFunction, double delay)
{
return this._eventQueue.Enqueue(new CallBackEvent(callBackFunction, delay, CallBackType.TimeOut)).Id;
}
/// <summary>
/// https://developer.mozilla.org/en-US/docs/Web/API/window.clearTimeout
/// </summary>
/// <param name="id"></param>
private void __clearTimeout__(int id)
{
this._eventQueue.ClearCallBackEvent(id);
}
private void __clearInterval__(int id)
{
this._eventQueue.ClearCallBackEvent(id);
}
#endregion
}
}