Repository navigation
Expand file tree
/
Copy pathWpfHotReloadAgent.cs
More file actions
3649 lines (3221 loc) · 132 KB
/
Copy pathWpfHotReloadAgent.cs
File metadata and controls
3649 lines (3221 loc) · 132 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
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
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Pipes;
using System.Linq;
using System.Runtime.InteropServices;
using System.Reflection;
#if NET5_0_OR_GREATER
using System.Reflection.Metadata;
#endif
using System.Text;
#if !NETFRAMEWORK
using System.Text.Json;
#endif
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Interop;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Media3D;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using System.Xaml;
using System.Xml.Linq;
using System.Xml;
namespace WpfHotReload.Runtime;
public static class WpfHotReloadAgent
{
private static readonly object LogSync = new();
private static volatile bool _pipeListenerRunning;
private static CancellationTokenSource? _pipeCts;
private static HotReloadOverlayWindow? _overlay;
private static bool _previewHostHiddenByAgent;
private static int _initialHideWorkerStarted;
private static int _overlayStartupWorkerStarted;
private static readonly bool _startHiddenRequested = ReadBooleanEnvironmentVariable("WPF_HOTRELOAD_START_HIDDEN");
private static readonly string? LogPath = Environment.GetEnvironmentVariable("WPF_HOTRELOAD_LOG");
// ── Source Map ──────────────────────────────────────────────────────
// Maps (normalized file path, line, column) → WeakReference to the live object.
// Built via VisualDiagnostics.GetXamlSourceInfo when ENABLE_XAML_DIAGNOSTICS_SOURCE_INFO=1.
private static readonly Dictionary<SourceAnchor, WeakReference<DependencyObject>> _sourceMap = new();
private static readonly object _sourceMapLock = new();
// Per XAML file, the last text whose apply succeeded: what a failed merge is rolled back to.
// Only touched on the UI thread (every apply runs through the application's dispatcher).
private static readonly Dictionary<string, string> _lastGoodXaml = new(StringComparer.OrdinalIgnoreCase);
// Test-only fault injection: when set, an apply whose XAML contains this text throws after the
// live tree was merged, which is what a real failure half-way through a merge looks like.
private static readonly string? _faultAfterMergeMarker =
Environment.GetEnvironmentVariable("WPF_HOTRELOAD_TEST_FAULT_AFTER_MERGE");
private static volatile bool _sourceMapBuilt;
private static volatile MethodInfo? _getXamlSourceInfoMethod;
private static volatile MethodInfo? _getResourceDictionariesForSourceMethod;
private static volatile bool _diagnosticMethodsResolved;
public static string PipeName { get; } =
Environment.GetEnvironmentVariable("WPF_HOTRELOAD_PIPE")
?? $"wpf-hotreload-{Process.GetCurrentProcess().Id}";
#if !NETFRAMEWORK
private static readonly JsonSerializerOptions JsonOptions = new()
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
};
#endif
private static void Log(string message)
{
var line = $"[WpfHotReload] {DateTime.Now:O} {message}";
Debug.WriteLine(line);
if (string.IsNullOrWhiteSpace(LogPath))
{
return;
}
try
{
lock (LogSync)
{
var logDir = Path.GetDirectoryName(LogPath);
if (!string.IsNullOrWhiteSpace(logDir))
{
Directory.CreateDirectory(logDir);
}
File.AppendAllText(LogPath, line + Environment.NewLine, Encoding.UTF8);
}
}
catch
{
// Never let diagnostics break the host app.
}
}
// ── Source Map Types and Methods ──────────────────────────────────────
private readonly struct SourceAnchor : IEquatable<SourceAnchor>
{
public string NormalizedUri { get; }
public int Line { get; }
public int Column { get; }
public SourceAnchor(string normalizedUri, int line, int column)
{
NormalizedUri = normalizedUri;
Line = line;
Column = column;
}
public bool Equals(SourceAnchor other) =>
Line == other.Line && Column == other.Column &&
string.Equals(NormalizedUri, other.NormalizedUri, StringComparison.Ordinal);
public override bool Equals(object? obj) => obj is SourceAnchor other && Equals(other);
public override int GetHashCode()
{
unchecked
{
var hash = NormalizedUri?.GetHashCode() ?? 0;
hash = (hash * 397) ^ Line;
hash = (hash * 397) ^ Column;
return hash;
}
}
}
private static void ResolveDiagnosticMethods()
{
if (_diagnosticMethodsResolved)
{
return;
}
_diagnosticMethodsResolved = true;
try
{
// VisualDiagnostics.GetXamlSourceInfo is in PresentationCore.
var vdType = typeof(System.Windows.Media.Visual).Assembly
.GetType("System.Windows.Diagnostics.VisualDiagnostics");
if (vdType is not null)
{
_getXamlSourceInfoMethod = vdType.GetMethod(
"GetXamlSourceInfo",
BindingFlags.Public | BindingFlags.Static,
binder: null,
types: new[] { typeof(object) },
modifiers: null);
Log($"Resolved VisualDiagnostics.GetXamlSourceInfo: {_getXamlSourceInfoMethod is not null}");
}
// ResourceDictionaryDiagnostics.GetResourceDictionariesForSource is in PresentationFramework.
var rddType = typeof(Application).Assembly
.GetType("System.Windows.Diagnostics.ResourceDictionaryDiagnostics");
if (rddType is not null)
{
_getResourceDictionariesForSourceMethod = rddType.GetMethod(
"GetResourceDictionariesForSource",
BindingFlags.Public | BindingFlags.Static,
binder: null,
types: new[] { typeof(Uri) },
modifiers: null);
Log($"Resolved ResourceDictionaryDiagnostics.GetResourceDictionariesForSource: {_getResourceDictionariesForSourceMethod is not null}");
}
}
catch (Exception ex)
{
Log($"Failed to resolve diagnostic methods: {ex.Message}");
}
}
/// <summary>
/// Builds a source map from live objects to their XAML source locations.
/// Requires ENABLE_XAML_DIAGNOSTICS_SOURCE_INFO=1 to be set before app start.
/// </summary>
private static void BuildSourceMap()
{
ResolveDiagnosticMethods();
if (_getXamlSourceInfoMethod is null)
{
Log("Source map: GetXamlSourceInfo not available, skipping.");
return;
}
lock (_sourceMapLock)
{
_sourceMap.Clear();
var count = 0;
foreach (var candidate in EnumerateLiveCandidates())
{
if (candidate is not DependencyObject depObj)
{
continue;
}
try
{
var sourceInfo = _getXamlSourceInfoMethod.Invoke(null, new object[] { depObj });
if (sourceInfo is null)
{
continue;
}
// XamlSourceInfo has SourceUri (Uri), LineNumber (int), LinePosition (int).
var sourceInfoType = sourceInfo.GetType();
var sourceUri = sourceInfoType.GetProperty("SourceUri")?.GetValue(sourceInfo) as Uri;
var lineNumber = (int)(sourceInfoType.GetProperty("LineNumber")?.GetValue(sourceInfo) ?? 0);
var linePosition = (int)(sourceInfoType.GetProperty("LinePosition")?.GetValue(sourceInfo) ?? 0);
if (sourceUri is null || lineNumber == 0)
{
continue;
}
var normalizedUri = NormalizeSourceUri(sourceUri);
var anchor = new SourceAnchor(normalizedUri, lineNumber, linePosition);
_sourceMap[anchor] = new WeakReference<DependencyObject>(depObj);
count++;
}
catch
{
// Skip objects that fail source info lookup.
}
}
_sourceMapBuilt = true;
Log($"Source map built: {count} entries.");
}
}
private static string NormalizeSourceUri(Uri uri)
{
// pack://application:,,,/... URIs need normalization to file paths.
// For file:// URIs, just return the local path.
if (uri.IsFile)
{
return uri.LocalPath.Replace('/', '\\').ToLowerInvariant();
}
// pack:// URIs — extract the component path.
return uri.ToString().ToLowerInvariant();
}
private static DependencyObject? FindBySourceAnchor(string filePath, int line, int column)
{
var normalizedPath = filePath.Replace('/', '\\').ToLowerInvariant();
var anchor = new SourceAnchor(normalizedPath, line, column);
lock (_sourceMapLock)
{
if (_sourceMap.TryGetValue(anchor, out var weakRef) &&
weakRef.TryGetTarget(out var target))
{
return target;
}
}
return null;
}
/// <summary>
/// Find all live ResourceDictionary instances loaded from the given source URI.
/// Uses ResourceDictionaryDiagnostics.GetResourceDictionariesForSource when available.
/// </summary>
private static IEnumerable<ResourceDictionary> FindResourceDictionariesForSource(string filePath)
{
ResolveDiagnosticMethods();
if (_getResourceDictionariesForSourceMethod is null)
{
yield break;
}
Uri sourceUri;
try
{
sourceUri = new Uri(filePath, UriKind.Absolute);
}
catch
{
yield break;
}
object? result;
try
{
result = _getResourceDictionariesForSourceMethod.Invoke(null, new object[] { sourceUri });
}
catch (Exception ex)
{
Log($"ResourceDictionaryDiagnostics.GetResourceDictionariesForSource failed: {ex.Message}");
yield break;
}
if (result is IEnumerable enumerable)
{
foreach (var item in enumerable)
{
if (item is null)
{
continue;
}
// Each item is a ResourceDictionaryInfo — extract the ResourceDictionary property.
var dictProp = item.GetType().GetProperty("ResourceDictionary");
if (dictProp?.GetValue(item) is ResourceDictionary dict)
{
yield return dict;
}
}
}
}
/// <summary>
/// Called by StartupHook once Application.Current is available.
/// Safe to call multiple times — only the first call starts the listener.
/// </summary>
public static void EnsurePipeListenerStarted()
{
Log($"EnsurePipeListenerStarted called, already running={_pipeListenerRunning}");
EnsureStartHiddenWorker();
EnsureOverlayStartupWorker();
if (_pipeListenerRunning)
{
return;
}
_pipeCts?.Cancel();
_pipeCts = new CancellationTokenSource();
var ct = _pipeCts.Token;
var name = PipeName;
var thread = new Thread(() => PipeListenerLoop(name, ct))
{
IsBackground = true,
Name = "WpfHotReloadPipeListener",
};
thread.Start();
_pipeListenerRunning = true;
Log($"Pipe listener thread started for {name}");
}
private static bool ReadBooleanEnvironmentVariable(string name)
{
var value = Environment.GetEnvironmentVariable(name);
if (string.IsNullOrWhiteSpace(value))
{
return false;
}
return string.Equals(value, "1", StringComparison.OrdinalIgnoreCase)
|| string.Equals(value, "true", StringComparison.OrdinalIgnoreCase)
|| string.Equals(value, "yes", StringComparison.OrdinalIgnoreCase)
|| string.Equals(value, "on", StringComparison.OrdinalIgnoreCase);
}
private static void EnsureStartHiddenWorker()
{
if (!_startHiddenRequested)
{
return;
}
if (Interlocked.Exchange(ref _initialHideWorkerStarted, 1) != 0)
{
return;
}
var worker = new Thread(HidePreviewHostOnStartupLoop)
{
IsBackground = true,
Name = "WpfHotReloadInitialHide",
};
worker.Start();
}
/// <summary>
/// Starts a one-time background thread that polls until the main window is loaded
/// and then injects the overlay toolbar. This runs independently of any pipe
/// connection so the overlay appears as soon as the app starts, not only after
/// the first Hot Reload click.
/// </summary>
private static void EnsureOverlayStartupWorker()
{
if (Interlocked.Exchange(ref _overlayStartupWorkerStarted, 1) != 0)
{
return;
}
var worker = new Thread(InjectOverlayOnStartupLoop)
{
IsBackground = true,
Name = "WpfHotReloadOverlayInit",
};
worker.Start();
}
private static void InjectOverlayOnStartupLoop()
{
var startedAt = Stopwatch.StartNew();
while (startedAt.Elapsed < TimeSpan.FromSeconds(30))
{
try
{
var app = Application.Current;
if (app is not null)
{
bool injected = app.Dispatcher.Invoke(() =>
{
if (_overlay is not null)
{
return true; // already done
}
var mainWindow = app.MainWindow;
if (mainWindow is null || !mainWindow.IsLoaded)
{
return false;
}
InjectOverlay(mainWindow);
return _overlay is not null;
});
if (injected)
{
return;
}
}
}
catch
{
// Keep retrying while app startup stabilizes.
}
Thread.Sleep(100);
}
}
private static void HidePreviewHostOnStartupLoop()
{
var startedAt = Stopwatch.StartNew();
while (startedAt.Elapsed < TimeSpan.FromSeconds(12))
{
try
{
var app = Application.Current;
if (app is not null)
{
var hidden = app.Dispatcher.Invoke(TryHidePreviewHostImmediately, DispatcherPriority.Send);
if (hidden)
{
return;
}
}
}
catch
{
// Keep retrying while app startup stabilizes.
}
Thread.Sleep(75);
}
}
private static bool TryHidePreviewHostImmediately()
{
if (!_startHiddenRequested)
{
return false;
}
var window = ResolvePreviewHostWindow();
if (window is null)
{
return false;
}
if (!window.IsLoaded)
{
window.Loaded -= OnPreviewHostLoadedHide;
window.Loaded += OnPreviewHostLoadedHide;
return false;
}
if (window.Visibility == Visibility.Visible)
{
window.Hide();
}
_previewHostHiddenByAgent = window.Visibility != Visibility.Visible;
return _previewHostHiddenByAgent;
}
private static void OnPreviewHostLoadedHide(object? sender, RoutedEventArgs args)
{
if (sender is not Window window)
{
return;
}
window.Loaded -= OnPreviewHostLoadedHide;
if (!_startHiddenRequested)
{
return;
}
if (window.Visibility == Visibility.Visible)
{
window.Hide();
}
_previewHostHiddenByAgent = window.Visibility != Visibility.Visible;
}
private static void PipeListenerLoop(string pipeName, CancellationToken ct)
{
Log($"PipeListenerLoop started, pipe={pipeName}");
while (!ct.IsCancellationRequested)
{
try
{
using var server = new NamedPipeServerStream(
pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte);
Log("Waiting for connection...");
server.WaitForConnection();
Log("Client connected");
// Inject the overlay toolbar on first connection (if not already injected).
EnsureOverlayInjected();
using var reader = new StreamReader(server, new UTF8Encoding(false));
using var writer = new StreamWriter(server, new UTF8Encoding(false)) { AutoFlush = true };
Log("Reading line...");
var line = reader.ReadLine();
Log($"Read line: {(line is null ? "(null)" : line.Substring(0, Math.Min(line.Length, 100)))}");
if (line is null)
{
continue;
}
string result;
string? responseValue = null;
try
{
var request = DeserializePipeRequest(line);
if (request is null)
{
result = "error: invalid request";
}
else if (string.Equals(request.Kind, "query", StringComparison.Ordinal))
{
result = "ok";
// Most queries read live DependencyObjects, which are owned by the UI
// thread; reading them straight from this pipe thread throws
// "The calling thread cannot access this object because a different
// thread owns it." The constant-valued queries (agent.ready and the
// diagnostics/sourceMap counters) happen to survive that, which is what
// made this look like a per-query quirk rather than a threading bug.
var queryApp = Application.Current;
if (queryApp is null)
{
// The agent listens from the startup hook, before the application
// exists. Application.Current can become non-null between the check
// above and the reads inside QueryValue, which would then touch
// MainWindow from this pipe thread and throw the cross-thread
// InvalidOperationException - failing the whole session on a race at
// startup. With no application yet, nothing is ready.
responseValue = string.Equals(request.Query, "agent.ready", StringComparison.Ordinal)
? "0"
: QueryValueWithoutApplication(request.Query);
}
else
{
responseValue = queryApp.Dispatcher.Invoke(() => QueryValue(request.Query));
}
}
else if (string.Equals(request.Kind, "preview", StringComparison.Ordinal))
{
var app = Application.Current;
if (app is null)
{
result = "error: no current WPF application";
}
else
{
PreviewCaptureResult previewResult;
if (string.Equals(request.Action, "hitTest", StringComparison.Ordinal))
{
previewResult = app.Dispatcher.Invoke(() => HitTestPreviewElement(request.FilePath, request.XNorm, request.YNorm));
}
else if (string.Equals(request.Action, "setHostVisibility", StringComparison.Ordinal))
{
previewResult = app.Dispatcher.Invoke(() => SetPreviewHostVisibility(request.Query));
}
else if (string.Equals(request.Action, "inspect", StringComparison.Ordinal))
{
previewResult = app.Dispatcher.Invoke(() => InspectPreviewElement(request.Query));
}
else if (string.Equals(request.Action, "find", StringComparison.Ordinal))
{
previewResult = app.Dispatcher.Invoke(() => FindPreviewElement(request.Query));
}
else
{
previewResult = app.Dispatcher.Invoke(() => CapturePreviewFrame(request.FilePath));
}
if (previewResult.Result.StartsWith("ok", StringComparison.Ordinal))
{
result = "ok";
responseValue = previewResult.Value;
}
else
{
result = previewResult.Result;
}
}
}
else if (string.Equals(request.Kind, "runUpdateHandlers", StringComparison.Ordinal))
{
// A debugger applied the delta (ICorDebugModule2::ApplyChanges), which runs no
// MetadataUpdateHandler: the IDE asks the agent to run them, as applyDelta does.
var app = Application.Current;
result = app is null
? "error: no current WPF application"
: app.Dispatcher.Invoke(() => RunUpdateHandlersCore(request));
}
else if (string.Equals(request.Kind, "applyDelta", StringComparison.Ordinal))
{
var app = Application.Current;
if (app is null)
{
result = "error: no current WPF application";
}
else
{
// Update handlers frequently invalidate WPF caches, so run the entire
// post-update sequence on the application's dispatcher.
result = app.Dispatcher.Invoke(() => ApplyDeltaCore(request));
}
}
else if (request.FilePath is null || request.XamlText is null)
{
result = "error: invalid request";
}
else
{
var app = Application.Current;
if (app is null)
{
result = "error: no current WPF application";
}
else
{
Log("Dispatching to UI thread...");
app.Dispatcher.Invoke(() => UpdateOverlayStatus(OverlayState.Applying, "Applying\u2026"));
result = app.Dispatcher.Invoke(() => ApplyXamlTextCore(request));
Log($"Dispatch result: {result}");
if (result.StartsWith("ok", StringComparison.Ordinal))
{
app.Dispatcher.Invoke(() => UpdateOverlayStatus(OverlayState.Applied, "Updated"));
}
else
{
app.Dispatcher.Invoke(() => UpdateOverlayStatus(OverlayState.Error, result));
}
}
}
}
catch (Exception ex)
{
result = $"error: {ex.GetType().Name}: {ex.Message}";
Log($"Exception: {result}");
}
Log("Writing response...");
writer.WriteLine(SerializePipeResponse(result, responseValue));
Log("Response written");
}
catch (OperationCanceledException)
{
break;
}
catch (Exception ex)
{
Log($"PipeListenerLoop error: {ex}");
// Connection broken, continue accepting
}
}
_pipeListenerRunning = false;
Log($"PipeListenerLoop stopped, pipe={pipeName}");
}
private static string ApplyDeltaCore(PipeRequest request)
{
if (!Guid.TryParse(request.Mvid, out var mvid)
|| request.Metadata is null || request.Metadata.Length == 0
|| request.Il is null || request.Il.Length == 0
|| request.Pdb is null || request.Pdb.Length == 0
|| request.UpdatedTypeTokens is null || request.UpdatedTypeTokens.Length == 0)
{
return "error: applyDelta needs mvid, metadata, il, pdb and updatedTypeTokens";
}
var assembly = AppDomain.CurrentDomain.GetAssemblies()
.FirstOrDefault(candidate => !candidate.IsDynamic && candidate.ManifestModule.ModuleVersionId == mvid);
if (assembly is null)
return "error: no loaded assembly has MVID " + mvid;
try
{
#if NET5_0_OR_GREATER
if (!MetadataUpdater.IsSupported)
return "error: MetadataUpdater is not supported; launch with DOTNET_MODIFIABLE_ASSEMBLIES=debug";
var handlers = FindMetadataUpdateHandlers(assembly);
var updatedTypes = ResolveUpdatedTypes(assembly, request.UpdatedTypeTokens);
foreach (var handler in handlers) InvokeMetadataUpdateHandler(handler, "ClearCache", updatedTypes);
MetadataUpdater.ApplyUpdate(assembly, request.Metadata, request.Il, request.Pdb);
foreach (var handler in handlers) InvokeMetadataUpdateHandler(handler, "UpdateApplication", updatedTypes);
return "ok: applied code delta to " + assembly.GetName().Name;
#else
return "error: MetadataUpdater is unavailable in this agent build";
#endif
}
catch (Exception ex)
{
Log("applyDelta failed: " + ex);
return "error: " + ex.GetType().Name + ": " + ex.Message;
}
}
private static string RunUpdateHandlersCore(PipeRequest request)
{
if (!Guid.TryParse(request.Mvid, out var mvid) || request.UpdatedTypeTokens is null)
{
return "error: runUpdateHandlers needs mvid and updatedTypeTokens";
}
var assembly = AppDomain.CurrentDomain.GetAssemblies()
.FirstOrDefault(candidate => !candidate.IsDynamic && candidate.ManifestModule.ModuleVersionId == mvid);
if (assembly is null)
return "error: no loaded assembly has MVID " + mvid;
try
{
var handlers = FindMetadataUpdateHandlers(assembly);
var updatedTypes = ResolveUpdatedTypes(assembly, request.UpdatedTypeTokens);
foreach (var handler in handlers) InvokeMetadataUpdateHandler(handler, "ClearCache", updatedTypes);
foreach (var handler in handlers) InvokeMetadataUpdateHandler(handler, "UpdateApplication", updatedTypes);
return $"ok: ran {handlers.Length} update handler(s) in " + assembly.GetName().Name;
}
catch (Exception ex)
{
Log("runUpdateHandlers failed: " + ex);
return "error: " + ex.GetType().Name + ": " + ex.Message;
}
}
private static Type[] ResolveUpdatedTypes(Assembly assembly, int[] tokens)
{
return tokens.Select(token => {
try { return assembly.ManifestModule.ResolveType(token); }
catch (ArgumentException) { return null; }
}).Where(type => type is not null).Cast<Type>().ToArray();
}
private static Type[] FindMetadataUpdateHandlers(Assembly assembly)
{
return assembly.GetCustomAttributesData()
.Where(attribute => attribute.AttributeType.FullName == "System.Reflection.Metadata.MetadataUpdateHandlerAttribute")
.Select(attribute => attribute.ConstructorArguments.Count == 1 ? attribute.ConstructorArguments[0].Value as Type : null)
.Where(type => type is not null).Cast<Type>().ToArray();
}
private static void InvokeMetadataUpdateHandler(Type handler, string name, Type[] updatedTypes)
{
var method = handler.GetMethod(name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static,
null, new[] { typeof(Type[]) }, null);
try { method?.Invoke(null, new object[] { updatedTypes }); }
catch (TargetInvocationException ex) when (ex.InnerException is not null) { throw ex.InnerException; }
}
private sealed class PipeRequest
{
public string? Kind { get; set; }
public string? Action { get; set; }
public string? FilePath { get; set; }
public string? XamlText { get; set; }
public string? PreviousXamlText { get; set; }
public string? ChangeKind { get; set; }
public List<PropertyChangeInfo>? PropertyChanges { get; set; }
public string? Query { get; set; }
public string? XNorm { get; set; }
public string? YNorm { get; set; }
public string? Mvid { get; set; }
public byte[]? Metadata { get; set; }
public byte[]? Il { get; set; }
public byte[]? Pdb { get; set; }
public int[]? UpdatedTypeTokens { get; set; }
}
private sealed class PropertyChangeInfo
{
public string ElementName { get; set; } = string.Empty;
public string ElementType { get; set; } = string.Empty;
public string Property { get; set; } = string.Empty;
public string NewValue { get; set; } = string.Empty;
public int Line { get; set; }
public int Column { get; set; }
}
private sealed class PipeResponse
{
public string? Result { get; set; }
public string? Value { get; set; }
}
private sealed class PreviewFrame
{
public string PngBase64 { get; set; } = string.Empty;
public int Width { get; set; }
public int Height { get; set; }
public string Source { get; set; } = "runtime-main-window";
}
private sealed class PreviewCaptureResult
{
public string Result { get; set; } = "error: unknown";
public string? Value { get; set; }
}
private sealed class PreviewHit
{
public string TypeName { get; set; } = string.Empty;
public string ElementName { get; set; } = string.Empty;
public double BoundsX { get; set; }
public double BoundsY { get; set; }
public double BoundsWidth { get; set; }
public double BoundsHeight { get; set; }
public double RootWidth { get; set; }
public double RootHeight { get; set; }
}
private sealed class PreviewProperties
{
public string TypeName { get; set; } = string.Empty;
public string ElementName { get; set; } = string.Empty;
public string Text { get; set; } = string.Empty;
public string Background { get; set; } = string.Empty;
public string Foreground { get; set; } = string.Empty;
public string Width { get; set; } = string.Empty;
public string Height { get; set; } = string.Empty;
public string ActualWidth { get; set; } = string.Empty;
public string ActualHeight { get; set; } = string.Empty;
public string Margin { get; set; } = string.Empty;
public string HorizontalAlignment { get; set; } = string.Empty;
public string VerticalAlignment { get; set; } = string.Empty;
public string IsEnabled { get; set; } = string.Empty;
public string Visibility { get; set; } = string.Empty;
public string CanEditText { get; set; } = "False";
public string CanEditBackground { get; set; } = "False";
public string CanEditForeground { get; set; } = "False";
}
// ── Overlay window ───────────────────────────────────────────────────
internal enum OverlayState
{
Connected,
Applying,
Applied,
Error,
Disconnected,
}
/// <summary>
/// Called from the pipe listener's background thread to inject the overlay
/// into the WPF app once Application.Current and MainWindow are available.
/// </summary>
internal static void EnsureOverlayInjected()
{
var app = Application.Current;
if (app is null)
{
return;
}
app.Dispatcher.Invoke(() =>
{
if (_overlay is not null)
{
return;
}
var mainWindow = app.MainWindow;
if (mainWindow is null || !mainWindow.IsLoaded)
{
// Retry when the window finishes loading.
if (mainWindow is not null)
{
mainWindow.Loaded += (_, _) =>
{
if (_overlay is null)
{
InjectOverlay(mainWindow);
}
};
}
return;
}
InjectOverlay(mainWindow);
});
}
private static void InjectOverlay(Window mainWindow)
{
try
{
_overlay = new HotReloadOverlayWindow(mainWindow);
_overlay.Show();
Log("Overlay injected into title bar.");
}
catch (Exception ex)
{
Log($"Failed to inject overlay: {ex.Message}");
}
}
private static void UpdateOverlayStatus(OverlayState state, string message)
{
_overlay?.UpdateStatus(state, message);
}
/// <summary>
/// A transparent, click-through window that sits over the host window's title bar
/// to show hot reload status — similar to the Visual Studio indicator.
/// </summary>
private sealed class HotReloadOverlayWindow : Window
{
// Win32 constants
private const int GWL_EXSTYLE = -20;
private const int WS_EX_TRANSPARENT = 0x00000020;
private const int WS_EX_NOACTIVATE = 0x08000000;
private const int WS_EX_TOOLWINDOW = 0x00000080;
[DllImport("user32.dll")]
private static extern int GetWindowLong(IntPtr hwnd, int nIndex);
[DllImport("user32.dll")]
private static extern int SetWindowLong(IntPtr hwnd, int nIndex, int dwNewLong);
private readonly Window _host;
private readonly System.Windows.Shapes.Path _label;
private readonly Border _border;
private DispatcherTimer? _fadeTimer;
public HotReloadOverlayWindow(Window host)
{
_host = host;
WindowStyle = WindowStyle.None;
AllowsTransparency = true;
Background = Brushes.Transparent;
ShowInTaskbar = false;
ResizeMode = ResizeMode.NoResize;
Focusable = false;
IsHitTestVisible = false;
Owner = host;
SizeToContent = SizeToContent.WidthAndHeight;
// Drawn as geometry, not text. The badge used a "Segoe UI" glyph and the fire emoji
// U+1F525, which is a Windows assumption twice over: that font does not exist on
// macOS or Linux, and a colour-emoji codepoint has no glyph in the portable host's
// text stack either - so the badge rendered as an empty replacement box, a
// meaningless rectangle sitting on the title bar. A Path needs no font at all.
_label = new System.Windows.Shapes.Path
{
Fill = Brushes.White,
Stretch = Stretch.Uniform,
Width = 10,
Height = 10,
Data = StateGeometry(OverlayState.Connected),
ToolTip = "Hot Reload active",
VerticalAlignment = VerticalAlignment.Center,
HorizontalAlignment = HorizontalAlignment.Center,