| | | 1 | | using System.Collections.Concurrent; |
| | | 2 | | using Microsoft.JSInterop; |
| | | 3 | | using UIBlazor.Services; |
| | | 4 | | using UIBlazor.Services.Settings; |
| | | 5 | | |
| | | 6 | | namespace UIBlazor.VS; |
| | | 7 | | |
| | | 8 | | public class VsBridge : IVsBridge, IDisposable |
| | | 9 | | { |
| | | 10 | | private readonly IJSRuntime _jsRuntime; |
| | | 11 | | private readonly ICommonSettingsProvider _commonOptions; |
| | | 12 | | private readonly IVsCodeContextService _vsCodeContextService; |
| | | 13 | | private DotNetObjectReference<VsBridge> _dotNetRef; |
| | | 14 | | private readonly ConcurrentDictionary<string, TaskCompletionSource<VsResponse>> _pendingRequests; |
| | | 15 | | private bool _isInitialized; |
| | | 16 | | |
| | 0 | 17 | | public VsBridge(IJSRuntime jsRuntime, |
| | 0 | 18 | | ICommonSettingsProvider commonSettingsProvider, |
| | 0 | 19 | | IVsCodeContextService vsCodeContextService) |
| | | 20 | | { |
| | 0 | 21 | | _jsRuntime = jsRuntime; |
| | 0 | 22 | | _commonOptions = commonSettingsProvider; |
| | 0 | 23 | | _vsCodeContextService = vsCodeContextService; |
| | 0 | 24 | | _pendingRequests = new ConcurrentDictionary<string, TaskCompletionSource<VsResponse>>(); |
| | 0 | 25 | | } |
| | | 26 | | |
| | | 27 | | public async Task InitializeAsync() |
| | | 28 | | { |
| | 0 | 29 | | if (!_isInitialized) |
| | | 30 | | { |
| | 0 | 31 | | _dotNetRef = DotNetObjectReference.Create(this); |
| | 0 | 32 | | var result = await _jsRuntime.InvokeAsync<string>("setVsBridgeHandler", _dotNetRef); |
| | 0 | 33 | | _isInitialized = result == "OK"; |
| | | 34 | | |
| | 0 | 35 | | if (_isInitialized) |
| | | 36 | | { |
| | | 37 | | // Notify Host that we are ready to receive messages (e.g. initial context) |
| | 0 | 38 | | await _jsRuntime.InvokeVoidAsync("postVsMessage", new VsRequest { Action = BasicEnum.UIReady }); |
| | | 39 | | } |
| | | 40 | | } |
| | 0 | 41 | | } |
| | | 42 | | |
| | | 43 | | public async Task<VsToolResult> ExecuteToolAsync(string name, IReadOnlyDictionary<string, object>? args = null, Canc |
| | | 44 | | { |
| | 0 | 45 | | var request = new VsRequest |
| | 0 | 46 | | { |
| | 0 | 47 | | Action = name, |
| | 0 | 48 | | Payload = args != null ? JsonUtils.Serialize(args) : null |
| | 0 | 49 | | }; |
| | | 50 | | |
| | 0 | 51 | | var response = await SendRequestAsync(request, cancellationToken); |
| | | 52 | | |
| | 0 | 53 | | return Convert(request, response); |
| | 0 | 54 | | } |
| | | 55 | | |
| | | 56 | | private VsToolResult Convert(VsRequest vsRequest, VsResponse vsResponse) |
| | | 57 | | { |
| | 0 | 58 | | return new VsToolResult |
| | 0 | 59 | | { |
| | 0 | 60 | | Args = vsRequest.Payload ?? string.Empty, |
| | 0 | 61 | | ErrorMessage = vsResponse.Error ?? string.Empty, |
| | 0 | 62 | | Name = vsRequest.Action, |
| | 0 | 63 | | Result = vsResponse.Payload ?? vsResponse.Error ?? string.Empty, |
| | 0 | 64 | | Success = vsResponse.Success |
| | 0 | 65 | | }; |
| | | 66 | | } |
| | | 67 | | |
| | | 68 | | private async Task<VsResponse> SendRequestAsync(VsRequest request, CancellationToken cancellationToken) |
| | | 69 | | { |
| | 0 | 70 | | await EnsureInitializedAsync(); |
| | | 71 | | |
| | 0 | 72 | | var tcs = new TaskCompletionSource<VsResponse>(); |
| | 0 | 73 | | _pendingRequests.TryAdd(request.CorrelationId, tcs); |
| | | 74 | | |
| | | 75 | | try |
| | | 76 | | { |
| | | 77 | | // Отправляем запрос |
| | 0 | 78 | | var result = await _jsRuntime.InvokeAsync<string>("postVsMessage", cancellationToken: cancellationToken, req |
| | | 79 | | |
| | 0 | 80 | | if (result != "OK") |
| | | 81 | | { |
| | 0 | 82 | | return new VsResponse |
| | 0 | 83 | | { |
| | 0 | 84 | | Success = false, |
| | 0 | 85 | | Error = $"WebView2 API is`t find." |
| | 0 | 86 | | }; |
| | | 87 | | } |
| | | 88 | | |
| | 0 | 89 | | var timeOut = TimeSpan.FromMilliseconds(_commonOptions.Current.ToolTimeoutMs); |
| | | 90 | | #if DEBUG |
| | | 91 | | // Дебаг не быстрый) |
| | | 92 | | timeOut = TimeSpan.FromDays(1); |
| | | 93 | | #endif |
| | 0 | 94 | | using var timeoutCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); |
| | 0 | 95 | | timeoutCts.CancelAfter(timeOut); |
| | 0 | 96 | | timeoutCts.Token.Register(() => |
| | 0 | 97 | | tcs.TrySetException(new TimeoutException("Request timed out"))); |
| | | 98 | | |
| | | 99 | | // Ждем ответа |
| | 0 | 100 | | return await tcs.Task; |
| | | 101 | | } |
| | 0 | 102 | | catch (Exception ex) |
| | | 103 | | { |
| | 0 | 104 | | return new VsResponse |
| | 0 | 105 | | { |
| | 0 | 106 | | Success = false, |
| | 0 | 107 | | Error = $"Error getting response: {ex.Message}" |
| | 0 | 108 | | }; |
| | | 109 | | } |
| | | 110 | | finally |
| | | 111 | | { |
| | | 112 | | // Удаляем из ожидающих запросов |
| | 0 | 113 | | _pendingRequests.TryRemove(request.CorrelationId, out _); |
| | | 114 | | } |
| | 0 | 115 | | } |
| | | 116 | | |
| | | 117 | | [JSInvokable("HandleVsMessage")] |
| | | 118 | | public Task HandleVsMessageAsync(VsMessage message) |
| | | 119 | | { |
| | 0 | 120 | | switch (message.Action) |
| | | 121 | | { |
| | | 122 | | case "UpdateCodeContext": |
| | 0 | 123 | | if (!string.IsNullOrEmpty(message.Payload)) |
| | | 124 | | { |
| | | 125 | | try |
| | | 126 | | { |
| | 0 | 127 | | var context = JsonUtils.Deserialize<VsCodeContext>(message.Payload); |
| | 0 | 128 | | if (context != null) |
| | | 129 | | { |
| | 0 | 130 | | _vsCodeContextService.UpdateContext(context); |
| | | 131 | | } |
| | 0 | 132 | | } |
| | 0 | 133 | | catch (Exception ex) |
| | | 134 | | { |
| | 0 | 135 | | Console.WriteLine($"Error deserializing VsCodeContext: {ex.Message}"); |
| | 0 | 136 | | } |
| | | 137 | | } |
| | | 138 | | break; |
| | | 139 | | default: |
| | 0 | 140 | | Console.WriteLine($"Unknown message action: {message.Action}"); |
| | | 141 | | break; |
| | | 142 | | } |
| | | 143 | | |
| | 0 | 144 | | return Task.CompletedTask; |
| | | 145 | | } |
| | | 146 | | |
| | | 147 | | [JSInvokable("HandleVsResponse")] |
| | | 148 | | public Task HandleVsResponseAsync(VsResponse response) |
| | | 149 | | { |
| | | 150 | | try |
| | | 151 | | { |
| | 0 | 152 | | if (string.IsNullOrEmpty(response.CorrelationId)) |
| | | 153 | | { |
| | 0 | 154 | | Console.WriteLine("Invalid response received"); |
| | 0 | 155 | | return Task.CompletedTask; |
| | | 156 | | } |
| | | 157 | | |
| | 0 | 158 | | if (_pendingRequests.TryRemove(response.CorrelationId, out var tcs)) |
| | | 159 | | { |
| | 0 | 160 | | if (response.Success) |
| | | 161 | | { |
| | 0 | 162 | | tcs.SetResult(response); |
| | | 163 | | } |
| | | 164 | | else |
| | | 165 | | { |
| | 0 | 166 | | tcs.SetException(new Exception(response.Error ?? "Request failed")); |
| | | 167 | | } |
| | | 168 | | } |
| | | 169 | | else |
| | | 170 | | { |
| | 0 | 171 | | Console.WriteLine($"No pending request found for correlationId: {response.CorrelationId}"); |
| | | 172 | | } |
| | 0 | 173 | | } |
| | 0 | 174 | | catch (Exception ex) |
| | | 175 | | { |
| | 0 | 176 | | Console.WriteLine($"Error handling VS response: {ex.Message}"); |
| | 0 | 177 | | } |
| | | 178 | | |
| | 0 | 179 | | return Task.CompletedTask; |
| | 0 | 180 | | } |
| | | 181 | | |
| | | 182 | | private async Task EnsureInitializedAsync() |
| | | 183 | | { |
| | 0 | 184 | | if (!_isInitialized) |
| | | 185 | | { |
| | 0 | 186 | | await InitializeAsync(); |
| | | 187 | | } |
| | 0 | 188 | | } |
| | | 189 | | |
| | | 190 | | public void Dispose() |
| | | 191 | | { |
| | 0 | 192 | | _dotNetRef?.Dispose(); |
| | | 193 | | |
| | | 194 | | // Отменяем все ожидающие запросы |
| | 0 | 195 | | foreach (var tcs in _pendingRequests.Values) |
| | | 196 | | { |
| | 0 | 197 | | tcs.TrySetCanceled(); |
| | | 198 | | } |
| | 0 | 199 | | _pendingRequests.Clear(); |
| | 0 | 200 | | } |
| | | 201 | | } |