-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBlazor.cs
453 lines (422 loc) · 21.3 KB
/
Blazor.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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reactive.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using HarmonyLib;
using Microsoft.AspNetCore.Components;
using RxFileSystemWatcher;
namespace LivingThing.LiveBlazor
{
public class LiveConfiguration
{
public string RazoGeneratorPath { get; set; }
public string ProjectConfiguration { get; set; }
public string WatchDirectory { get; set; }
public Func<Type, Type[]> Filter { get; set; }
}
internal class LiveComponentContext
{
public MethodInfo OriginalMethod { get; set; }
public Type OriginalTypeInference { get; set; }
public Type NewType { get; set; }
//public MethodInfo Replacer { get; set; }
public List<ComponentBase> Components { get; set; } = new List<ComponentBase>();
}
internal class ProjectInfo
{
public string Path { get; set; }
public string FileName { get; set; }
public string Type { get; set; }
}
public static class Blazor
{
static Dictionary<Type, LiveComponentContext> liveContexts = new Dictionary<Type, LiveComponentContext>();
public static bool Prefix(ComponentBase __instance)
{
var type = __instance.GetType();
if (liveContexts.ContainsKey(type))
{
var context = liveContexts[type];
if (!context.Components.Contains(__instance))
{
context.Components.Add(__instance);
}
}
//if (context.NewType != null)
//{
// Type newCompiledType = context.NewType;
// var newRenderTree = newCompiledType.GetMethod("BuildRenderTree", BindingFlags.NonPublic | BindingFlags.Instance);
// newRenderTree.Invoke(__instance, new object[] { null });
// return false;
//}
return true;
}
static IEnumerable<CodeInstruction> Replace(Type newType, ILGenerator generator, MethodBase originalMethod)
{
var newMethod = newType.GetMethod(originalMethod.Name, BindingFlags.NonPublic | BindingFlags.Instance);
var newInstructions = newMethod.GetInstructions();
var labelledInstructions = newInstructions.Where(l => l.Operand is Instruction);
Dictionary<Instruction, Label> instructionLabels = new Dictionary<Instruction, Label>();
foreach (var instruction in labelledInstructions)
{
instructionLabels[instruction.Operand as Instruction] = generator.DefineLabel();
}
foreach (var instruction in newInstructions)
{
Label label;
if (instructionLabels.TryGetValue(instruction, out label))
{
generator.MarkLabel(label);
}
switch (instruction.OpCode.OperandType)
{
default:
switch (instruction.Operand)
{
case bool i:
generator.Emit(instruction.OpCode, i == false ? 0 : 1);
break;
case byte i:
generator.Emit(instruction.OpCode, i);
break;
case sbyte i:
//STRANGE: pushing an int8 onto stack throws object reference exception
//so we change the instruction to push int32
if (instruction.OpCode == OpCodes.Ldc_I4_S)
{
generator.Emit(OpCodes.Ldc_I4, (int)i);
}
else
{
generator.Emit(instruction.OpCode, i);
}
break;
case int i:
generator.Emit(instruction.OpCode, i);
break;
case uint i:
generator.Emit(instruction.OpCode, i);
break;
case short i:
generator.Emit(instruction.OpCode, i);
break;
case long i:
generator.Emit(instruction.OpCode, i);
break;
case float i:
generator.Emit(instruction.OpCode, i);
break;
case double i:
generator.Emit(instruction.OpCode, i);
break;
case string i:
generator.Emit(instruction.OpCode, i);
break;
case Type i:
generator.Emit(instruction.OpCode, i);
break;
case MethodInfo i:
generator.Emit(instruction.OpCode, i);
break;
case ConstructorInfo i:
generator.Emit(instruction.OpCode, i);
break;
case FieldInfo i:
generator.Emit(instruction.OpCode, i);
break;
case Label i:
generator.Emit(instruction.OpCode, i);
break;
case Label[] i:
generator.Emit(instruction.OpCode, i);
break;
case LocalBuilder i:
generator.Emit(instruction.OpCode, i);
break;
case SignatureHelper i:
generator.Emit(instruction.OpCode, i);
break;
case LocalVariableInfo i:
generator.DeclareLocal(i.LocalType);
generator.Emit(instruction.OpCode, i.LocalIndex);
break;
//case ParameterInfo i:
// generator.Emit(instruction.OpCode, i.Position);
// break;
default:
if (instruction.Operand != null)
{
throw new Exception($"UnImplemented Instruction {instruction.OpCode} with operand {instruction.Operand}");
}
generator.Emit(instruction.OpCode);
break;
}
break;
case OperandType.ShortInlineBrTarget:
case OperandType.InlineBrTarget:
Label branchLabel = instructionLabels[instruction.Operand as Instruction];
generator.Emit(instruction.OpCode, branchLabel);
break;
}
}
//var newCodes = PatchProcessor.ReadMethodBody(newRenderTree);
//foreach(var code in newCodes)
//{
// switch (code.Key.OperandType)
// {
// default:
// switch (code.Value)
// {
// case bool i:
// generator.Emit(code.Key, i == false ? 0 : 1);
// break;
// case byte i:
// generator.Emit(code.Key, i);
// break;
// case sbyte i:
// //generator.Emit(code.Key, i);
// break;
// case int i:
// generator.Emit(code.Key, i);
// break;
// case uint i:
// generator.Emit(code.Key, i);
// break;
// case long i:
// generator.Emit(code.Key, i);
// break;
// case float i:
// generator.Emit(code.Key, i);
// break;
// case double i:
// generator.Emit(code.Key, i);
// break;
// case string i:
// generator.Emit(code.Key, i);
// break;
// case Type i:
// generator.Emit(code.Key, i);
// break;
// case MethodInfo i:
// generator.Emit(code.Key, i);
// break;
// default:
// if (code.Value != null)
// {
// }
// generator.Emit(code.Key);
// break;
// }
// break;
// case OperandType.ShortInlineBrTarget:
// case OperandType.InlineBrTarget:
// break;
// }
//}
return new CodeInstruction[] { new CodeInstruction(OpCodes.Ret) };
}
static Type currentType;
public static IEnumerable<CodeInstruction> ReplaceBuildRenderTree/*<TComponent>*/(IEnumerable<CodeInstruction> instructions, ILGenerator generator, MethodBase originalMethod)
{
var context = liveContexts[currentType];//[typeof(TComponent)];
Type newCompiledType = context.NewType;
return Replace(newCompiledType, generator, originalMethod);
}
static Type currentTypeInference;
public static IEnumerable<CodeInstruction> ReplaceTypeInference(IEnumerable<CodeInstruction> instructions, ILGenerator generator, MethodBase originalMethod)
{
return Replace(currentTypeInference, generator, originalMethod);
}
static ProjectInfo GetProjectPath(string path)
{
string fileName = null;
if (Directory.EnumerateFiles(path).Any(f =>
{
if (f.EndsWith(".csproj"))
{
fileName = f;
return true;
}
return false;
}))
{
var csproj = File.ReadAllText(fileName);
var match = Regex.Match(csproj, ".?<TargetFramework>(.+)</TargetFramework>.?");
string projectType = "netstandard2.1";
if (match.Success)
{
projectType = match.Groups[1].Value;
}
return new ProjectInfo()
{
Path = Path.GetFullPath(path),
FileName = fileName,
Type = projectType
};
}
path = path.Trim(new char[] {'/', '\\' }) + "/../";
return GetProjectPath(path);
}
static Harmony harmony;
static ObservableFileSystemWatcher watcher;
public static async Task Live(LiveConfiguration configuration = null)
{
//Extract LiveBlazor.zip to a temporary folter
//var stream = typeof(LiveBlazor).Assembly.GetManifestResourceStream("LivingThing.LiveBlazor.LiveBlazor.zip");
//var workingDirectory = Path.GetDirectoryName(Path.Combine(Environment.CurrentDirectory, "..", "LiveBlazor"));
//if (!Directory.Exists(workingDirectory))
//{
// Directory.CreateDirectory(workingDirectory);
//}
//var zipPath = Path.Combine(workingDirectory, "LiveBlazor.zip");
//FileStream fs = new FileStream(zipPath, FileMode.Create);
//stream.CopyTo(fs);
//fs.Close();
//stream.Close();
//ZipFile.ExtractToDirectory(zipPath, workingDirectory, true);
////prebuild project enabling restore, so we dont have to restor anymore, which is faster
//$"cd {workingDirectory} & dotnet build".Bash();
harmony = new Harmony("com.liveblazor.livingthing");
var compiler = new Compiler();
var invokeAsync = typeof(ComponentBase).GetMethod("InvokeAsync", bindingAttr:BindingFlags.NonPublic | BindingFlags.Instance, types:new Type[] { typeof(Action) }, binder:null, modifiers:null);
var stateHasChanged = typeof(ComponentBase).GetMethod("StateHasChanged", BindingFlags.NonPublic | BindingFlags.Instance);
//find all components in all assemblies
var componentTypes = AppDomain.CurrentDomain.GetAssemblies().SelectMany(a => a.GetTypes()).Where(t => !t.IsAbstract && t.MemberType == MemberTypes.TypeInfo && typeof(ComponentBase).IsAssignableFrom(t)).ToArray();
var prefix = typeof(Blazor).GetMethod(nameof(Prefix));
foreach (var _type in componentTypes)
{
var types = configuration?.Filter?.Invoke(_type) ?? new Type[] { _type };
foreach (var type in types)
{
if (!typeof(ComponentBase).IsAssignableFrom(type))
{
throw new InvalidOperationException($"Type {type} is not a Component");
}
if (!type.ContainsGenericParameters)
{
var renderTree = type.GetMethod("BuildRenderTree", BindingFlags.NonPublic | BindingFlags.Instance);
if (renderTree.DeclaringType == type)
{
if (type.Name == "DeviceListItem")
{
}
var context = new LiveComponentContext()
{
OriginalMethod = type.GetMethod("BuildRenderTree", BindingFlags.NonPublic | BindingFlags.Instance),
OriginalTypeInference = type.Assembly.GetType("__Blazor." + type.FullName + ".TypeInference"),
};
liveContexts[type] = context;
harmony.Patch(renderTree, new HarmonyMethod(prefix));
}
}
}
}
string watchPath = configuration?.WatchDirectory ?? Environment.CurrentDirectory;
if (configuration?.WatchDirectory == null)
{
var solutionPath = Path.GetFullPath(Path.Combine(watchPath, "../"));
if (Directory.EnumerateFiles(solutionPath).Any(f=> f.EndsWith(".sln")))
{
watchPath = solutionPath;
}
}
watcher = new ObservableFileSystemWatcher(c =>
{
c.Path = watchPath;
c.IncludeSubdirectories = true;
c.Filter = "*.razor";
c.NotifyFilter = NotifyFilters.Attributes |
NotifyFilters.CreationTime |
NotifyFilters.FileName |
NotifyFilters.LastAccess |
NotifyFilters.LastWrite |
NotifyFilters.Size |
NotifyFilters.Security;
//c.Filters.Add("*.razor");
});
var changes = watcher.Changed.Throttle(TimeSpan.FromSeconds(.5));
string dotnetPath = (await "where dotnet".CLI()).StdOut.Trim();
string dotnetVersion = (await "dotnet --version".CLI()).StdOut.Trim();
var dotnetFolder = Path.GetDirectoryName(dotnetPath) + "\\";
var buildRenderTreeMethodPatcher = typeof(Blazor).GetMethod(nameof(ReplaceBuildRenderTree));
var typeInferenceMethodsPatcher = typeof(Blazor).GetMethod(nameof(ReplaceTypeInference));
changes.Subscribe(async filepath =>
{
string razorGeneratePath = configuration?.RazoGeneratorPath ?? @$"{dotnetFolder}sdk\{dotnetVersion}\Sdks\Microsoft.NET.Sdk.Razor\tools\netcoreapp3.0\rzc.dll";
var project = GetProjectPath(Path.GetDirectoryName(filepath.FullPath));
string projectName = Path.GetFileNameWithoutExtension(project.FileName);
var workspace = $"obj\\Debug\\{project.Type}\\";
var workingDirectory = $"{project.Path}{workspace}";
var outputPath = $"{workingDirectory}{Path.GetFileName(filepath.FullPath)}.g.cs";
string filePathInProject = filepath.FullPath.Replace(project.Path, "");
var @namespace = projectName;
string compile = $"dotnet exec \"{razorGeneratePath}\" generate -s \"{filepath.FullPath}\" -r \"{filePathInProject}\" -o \"{outputPath}\" -k component -p {project.Path} -v 3.0 -c {configuration?.ProjectConfiguration??"Default"} --root-namespace {@namespace} -t \"{workspace}{projectName}.TagHelpers.output.cache\"";
await $"cd {project.Path} & {compile}".CLI();
var file = File.ReadAllText(outputPath);
List<string> sourceCodes = new List<string>() { file };
var csFile = Path.ChangeExtension(filepath.FullPath, ".razor.cs");
if (File.Exists(csFile))
{
var csFileContent = File.ReadAllText(csFile);
sourceCodes.Add(csFileContent);
}
var code = compiler.Compile(sourceCodes.ToArray());
using (var asm = new MemoryStream(code))
{
var assemblyLoadContext = new UnloadableAssemblyLoadContext();
var assembly = assemblyLoadContext.LoadFromStream(asm);
// var assembly = Assembly.Load(code);//.LoadFromStream(asm);
Type newType = assembly.ExportedTypes.First(t => t.Name == Path.GetFileNameWithoutExtension(filepath.Name));
//Type newType = AppDomain.CurrentDomain.GetAssemblies().SelectMany(a => a.GetTypes()).First(t => t.Name == Path.GetFileNameWithoutExtension(filepath.Name));
assemblyLoadContext.Unload();
Type originalType = componentTypes.FirstOrDefault(t => t.FullName == newType.FullName);
if (originalType != null)
{
LiveComponentContext context = null;
liveContexts.TryGetValue(originalType, out context);
if (context != null)
{
context.NewType = newType;
currentType = originalType;
try
{
harmony.Patch(context.OriginalMethod, transpiler: new HarmonyMethod(buildRenderTreeMethodPatcher));
//patch all anonymous method of this type
//var anonymousMethods =
//pathch typeInference class
Type inferenceType = assembly.DefinedTypes.FirstOrDefault(t => t.Name == "TypeInference");
if (inferenceType != null && context.OriginalTypeInference != null)
{
currentTypeInference = inferenceType;
var methods = inferenceType.GetMethods();
foreach (var method in methods)
{
var originalMethod = context.OriginalTypeInference.GetMethod(method.Name);
harmony.Patch(originalMethod, transpiler: new HarmonyMethod(typeInferenceMethodsPatcher));
}
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.WriteLine(e.StackTrace);
return;
}
context.Components.ForEach(c =>
{
Action rerender = () => stateHasChanged.Invoke(c, new object[] { });
invokeAsync.Invoke(c, new object[] { rerender });
});
}
}
}
});
watcher.Start();
}
}
}