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