@nativescript/windows 0.1.0-alpha.61 → 0.1.0-alpha.63

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,8 @@
1
1
  using System;
2
2
  using System.Collections.Concurrent;
3
3
  using System.Collections.Generic;
4
+ using System.Linq;
5
+ using System.Linq.Expressions;
4
6
  using System.Reflection;
5
7
  using System.Threading.Tasks;
6
8
 
@@ -10,10 +12,6 @@ public static partial class Bridge
10
12
  {
11
13
  private static readonly ConcurrentDictionary<Type, Func<object, Task>?> s_awaitableCache = new();
12
14
 
13
- // Invoked when the binary instance call "__dotnet_await__(resolveId, rejectId)" arrives.
14
- // Converts any awaitable handle (Task<T>, ValueTask<T>, IAsyncOperation<T>, …) into an
15
- // async continuation that calls back into V8 via s_jsInvoker when it completes —
16
- // without blocking the main thread.
17
15
  internal static void ScheduleTaskContinuation(int handleId, int resolveId, int rejectId)
18
16
  {
19
17
  if (!s_handles.TryGetValue(handleId, out var obj) || obj is null)
@@ -22,7 +20,7 @@ public static partial class Bridge
22
20
  var task = GetTaskForAwaitable(obj)
23
21
  ?? throw new InvalidOperationException(
24
22
  $"Object of type {obj.GetType().FullName} is not awaitable. " +
25
- $"Expected Task<T>, ValueTask<T>, or any type implementing GetAwaiter().");
23
+ $"Expected Task<T>, ValueTask<T>, IAsyncOperation<T>, or any type implementing GetAwaiter().");
26
24
 
27
25
  task.ContinueWith(completed =>
28
26
  {
@@ -50,10 +48,6 @@ public static partial class Bridge
50
48
  }, TaskScheduler.Default);
51
49
  }
52
50
 
53
- // Converts any awaitable to a Task<object?> using the GetAwaiter() pattern via
54
- // reflection. Handles Task<T>, ValueTask<T>, WinRT IAsyncOperation<T>, and any
55
- // custom awaitable without requiring compile-time type knowledge. Results are
56
- // cached per awaitable type so reflection only runs on the first encounter.
57
51
  private static Task? GetTaskForAwaitable(object obj)
58
52
  {
59
53
  if (obj is Task t) return t;
@@ -63,12 +57,12 @@ public static partial class Bridge
63
57
  if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(ValueTask<>))
64
58
  return ValueTaskAsTaskCache.AsTask(type, obj);
65
59
 
60
+ var winrtTask = WinRtAsyncCache.TryGetTask(type, obj);
61
+ if (winrtTask != null) return winrtTask;
62
+
66
63
  return s_awaitableCache.GetOrAdd(type, BuildAwaitableFactory)?.Invoke(obj);
67
64
  }
68
65
 
69
- // Builds a factory that wraps an arbitrary awaitable type in a
70
- // TaskCompletionSource<object?>. Works for any type with GetAwaiter() returning
71
- // an object that has IsCompleted, GetResult(), and OnCompleted/UnsafeOnCompleted.
72
66
  private static Func<object, Task>? BuildAwaitableFactory(Type type)
73
67
  {
74
68
  var getAwaiter = type.GetMethod("GetAwaiter",
@@ -101,7 +95,7 @@ public static partial class Bridge
101
95
  {
102
96
  tcs.SetResult(getResult?.Invoke(awaiter, null));
103
97
  }
104
- catch (System.Reflection.TargetInvocationException ex)
98
+ catch (TargetInvocationException ex)
105
99
  {
106
100
  tcs.SetException(ex.InnerException ?? ex);
107
101
  }
@@ -119,3 +113,95 @@ public static partial class Bridge
119
113
  };
120
114
  }
121
115
  }
116
+
117
+ internal static class WinRtAsyncCache
118
+ {
119
+ private static readonly ConcurrentDictionary<Type, Func<object, Task>?> s_cache = new();
120
+
121
+ public static Task? TryGetTask(Type type, object obj)
122
+ => s_cache.GetOrAdd(type, BuildFactory)?.Invoke(obj);
123
+
124
+ private static Func<object, Task>? BuildFactory(Type type)
125
+ {
126
+ foreach (var iface in type.GetInterfaces())
127
+ {
128
+ var ifn = iface.FullName ?? "";
129
+ if (!ifn.StartsWith("Windows.Foundation.IAsync", StringComparison.Ordinal)) continue;
130
+
131
+ var completedProp = iface.GetProperty("Completed");
132
+ if (completedProp?.GetSetMethod() is not { } setter) continue;
133
+
134
+ var delegateType = completedProp.PropertyType;
135
+ var delegateInvoke = delegateType.GetMethod("Invoke");
136
+ if (delegateInvoke == null) continue;
137
+
138
+ var dp = delegateInvoke.GetParameters()
139
+ .Select(p => Expression.Parameter(p.ParameterType))
140
+ .ToArray();
141
+
142
+ if (iface.IsGenericType)
143
+ {
144
+ var resultType = iface.GetGenericArguments()[0];
145
+ var getResults = iface.GetMethod("GetResults");
146
+ if (getResults == null) continue;
147
+
148
+ var tcsType = typeof(TaskCompletionSource<>).MakeGenericType(resultType);
149
+ var taskProp = tcsType.GetProperty("Task")!;
150
+ var completeM = typeof(WinRtAsyncCache)
151
+ .GetMethod(nameof(CompleteResult), BindingFlags.NonPublic | BindingFlags.Static)!
152
+ .MakeGenericMethod(resultType);
153
+
154
+ return obj =>
155
+ {
156
+ var tcs = Activator.CreateInstance(tcsType, TaskCreationOptions.RunContinuationsAsynchronously)!;
157
+ var body = Expression.Call(completeM,
158
+ Expression.Constant(tcs),
159
+ Expression.Convert(dp[0], typeof(object)),
160
+ Expression.Convert(dp[1], typeof(int)),
161
+ Expression.Constant(getResults));
162
+ setter.Invoke(obj, [Expression.Lambda(delegateType, body, dp).Compile()]);
163
+ return (Task)taskProp.GetValue(tcs)!;
164
+ };
165
+ }
166
+ else
167
+ {
168
+ var completeM = typeof(WinRtAsyncCache)
169
+ .GetMethod(nameof(CompleteAction), BindingFlags.NonPublic | BindingFlags.Static)!;
170
+
171
+ return obj =>
172
+ {
173
+ var tcs = new TaskCompletionSource<object?>(TaskCreationOptions.RunContinuationsAsynchronously);
174
+ var body = Expression.Call(completeM,
175
+ Expression.Constant(tcs),
176
+ Expression.Convert(dp[1], typeof(int)));
177
+ setter.Invoke(obj, [Expression.Lambda(delegateType, body, dp).Compile()]);
178
+ return tcs.Task;
179
+ };
180
+ }
181
+ }
182
+ return null;
183
+ }
184
+
185
+ private static void CompleteResult<T>(object tcs, object sender, int status, MethodInfo getResults)
186
+ {
187
+ var typed = (TaskCompletionSource<T>)tcs;
188
+ try
189
+ {
190
+ if (status == 1)
191
+ typed.TrySetResult((T)getResults.Invoke(sender, null)!);
192
+ else if (status == 2)
193
+ typed.TrySetCanceled();
194
+ else
195
+ typed.TrySetException(new Exception($"WinRT async operation failed (status {status})"));
196
+ }
197
+ catch (TargetInvocationException ex) { typed.TrySetException(ex.InnerException ?? ex); }
198
+ catch (Exception ex) { typed.TrySetException(ex); }
199
+ }
200
+
201
+ private static void CompleteAction(TaskCompletionSource<object?> tcs, int status)
202
+ {
203
+ if (status == 1) tcs.TrySetResult(null);
204
+ else if (status == 2) tcs.TrySetCanceled();
205
+ else tcs.TrySetException(new Exception($"WinRT async action failed (status {status})"));
206
+ }
207
+ }
@@ -4,6 +4,8 @@ using System.Collections.Generic;
4
4
  using System.IO;
5
5
  using System.Linq;
6
6
  using System.Reflection;
7
+ using System.Threading;
8
+ using System.Threading.Tasks;
7
9
  using System.Runtime.InteropServices;
8
10
  using System.Runtime.Loader;
9
11
  using System.Text.Json;
@@ -159,6 +161,118 @@ public static partial class Bridge
159
161
  }
160
162
  }
161
163
 
164
+ public static object? RunOnUIThread(int callbackId)
165
+ {
166
+ var action = new Action(() =>
167
+ {
168
+ unsafe
169
+ {
170
+ if (s_jsInvoker == null) return;
171
+ byte* respPtr = null;
172
+ int respLen = 0;
173
+ s_jsInvoker(callbackId, null, 0, &respPtr, &respLen);
174
+ if (respPtr != null && respLen > 0) Marshal.FreeHGlobal((IntPtr)respPtr);
175
+ }
176
+ });
177
+
178
+ try
179
+ {
180
+ foreach (var asm in AppDomain.CurrentDomain.GetAssemblies())
181
+ {
182
+ var coreAppType = asm.GetType("Windows.ApplicationModel.Core.CoreApplication");
183
+ if (coreAppType == null) continue;
184
+ var mainViewProp = coreAppType.GetProperty("MainView", BindingFlags.Public | BindingFlags.Static);
185
+ var mainView = mainViewProp?.GetValue(null);
186
+ if (mainView == null) continue;
187
+ var dispatcherProp = mainView.GetType().GetProperty("Dispatcher", BindingFlags.Public | BindingFlags.Instance);
188
+ var dispatcher = dispatcherProp?.GetValue(mainView);
189
+ if (dispatcher == null) continue;
190
+
191
+ var hasAccessProp = dispatcher.GetType().GetProperty("HasThreadAccess", BindingFlags.Public | BindingFlags.Instance);
192
+ if (hasAccessProp?.GetValue(dispatcher) is true)
193
+ {
194
+ action();
195
+ return null;
196
+ }
197
+
198
+ foreach (var m in dispatcher.GetType().GetMethods().Where(m => m.Name == "RunAsync"))
199
+ {
200
+ var parameters = m.GetParameters();
201
+ if (parameters.Length != 2) continue;
202
+ var enumType = parameters[0].ParameterType;
203
+ object priority = enumType.IsEnum ? Enum.ToObject(enumType, 0) : Activator.CreateInstance(enumType)!;
204
+ var handlerType = parameters[1].ParameterType;
205
+ var mre = new ManualResetEventSlim(false);
206
+ var wrapped = new Action(() => { try { action(); } finally { mre.Set(); } });
207
+ try
208
+ {
209
+ var d = Delegate.CreateDelegate(handlerType, wrapped.Target, wrapped.Method);
210
+ m.Invoke(dispatcher, new object[] { priority, d });
211
+ mre.Wait();
212
+ return null;
213
+ }
214
+ catch { }
215
+ }
216
+ break;
217
+ }
218
+ }
219
+ catch { }
220
+
221
+ try
222
+ {
223
+ foreach (var asm in AppDomain.CurrentDomain.GetAssemblies())
224
+ {
225
+ var dqType = asm.GetType("Microsoft.UI.Dispatching.DispatcherQueue");
226
+ if (dqType == null) continue;
227
+ var getForCurrent = dqType.GetMethod("GetForCurrentThread", BindingFlags.Public | BindingFlags.Static);
228
+ var dq = getForCurrent?.Invoke(null, null);
229
+ if (dq == null) continue;
230
+
231
+ if (dq.GetType().GetProperty("HasThreadAccess")?.GetValue(dq) is true)
232
+ {
233
+ action();
234
+ return null;
235
+ }
236
+ break;
237
+ }
238
+ }
239
+ catch { }
240
+
241
+ try
242
+ {
243
+ var wpfDispatcherType = AppDomain.CurrentDomain.GetAssemblies()
244
+ .Select(a => a.GetType("System.Windows.Threading.Dispatcher"))
245
+ .FirstOrDefault(t => t != null);
246
+ if (wpfDispatcherType != null)
247
+ {
248
+ var currentDispatcherProp = wpfDispatcherType.GetProperty("CurrentDispatcher", BindingFlags.Public | BindingFlags.Static);
249
+ var dispatcher = currentDispatcherProp?.GetValue(null);
250
+ if (dispatcher != null)
251
+ {
252
+ var checkAccess = dispatcher.GetType().GetMethod("CheckAccess");
253
+ if (checkAccess?.Invoke(dispatcher, null) is true)
254
+ {
255
+ action();
256
+ return null;
257
+ }
258
+ var beginInvoke = dispatcher.GetType().GetMethod("BeginInvoke", new[] { typeof(Action) })
259
+ ?? dispatcher.GetType().GetMethods().FirstOrDefault(m => m.Name == "BeginInvoke" && m.GetParameters().Length == 1);
260
+ if (beginInvoke != null)
261
+ {
262
+ var mre = new ManualResetEventSlim(false);
263
+ beginInvoke.Invoke(dispatcher, new object[] { new Action(() => { try { action(); } finally { mre.Set(); } }) });
264
+ mre.Wait();
265
+ return null;
266
+ }
267
+ }
268
+ }
269
+ }
270
+ catch { }
271
+
272
+ action();
273
+ return null;
274
+ }
275
+
162
276
  private static Assembly? OnAssemblyResolve(object? sender, ResolveEventArgs args)
163
277
  {
164
278
  try
Binary file
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nativescript/windows",
3
- "version": "0.1.0-alpha.61",
3
+ "version": "0.1.0-alpha.63",
4
4
  "description": "NativeScript for using Windows v8",
5
5
  "repository": {
6
6
  "type": "git",