-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMain.cs
More file actions
785 lines (716 loc) · 28.3 KB
/
Main.cs
File metadata and controls
785 lines (716 loc) · 28.3 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
using AngleSharp.Dom;
using Microsoft.Web.WebView2.Core;
using Microsoft.Web.WebView2.WinForms;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Drawing.Imaging;
using System.Net.Http;
using System.Runtime.InteropServices;
using System.Security.Policy;
using System.Text;
using System.Text.Json;
using System.Xml.Linq;
using WebWrap.Controllers;
using WebWrap.Models;
namespace WebWrap
{
public partial class Main : Form
{
private readonly HttpClient _httpClient = new();
public HttpController? httpController;
private ConcurrentBag<PwshProcess> processList = new ConcurrentBag<PwshProcess>();
private CancellationTokenSource _asyncOutputCts;
private Task _asyncOutputTask;
const string MSG_HTTP_REQUEST = "httpRequest";
const string MSG_BRWS_RELOAD = "brwsReload";
const string MSG_PWSH_NEW = "pwshNew";
const string MSG_PWSH_INPUT = "pwshInput";
const string MSG_PWSH_KILL = "pwshKill";
const string MSG_PWSH_STOP = "pwshStop";
const string MSG_PWSH_ASYNC_OUTPUT = "pwshAsyncOutput";
const string MSG_TYPE_PWSH_RESULT = "pwshResult";
const string MSG_FILE_WRITE = "fileWrite";
const string MSG_FILE_READ = "fileRead";
const string MSG_FILE_TEXT_SEARCH = "fileTextSearch";
const string MSG_SYS_INFO = "sysInfo";
const string MSG_RAW_TO_MD = "rawToMd";
const string MSG_TYPE_ERROR = "error";
private static readonly JsonSerializerOptions JsonOptions = new()
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
WriteIndented = true
};
private object _processListLock = new object();
public Main()
{
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
InitializeComponent();
TitleBarController.EnableDarkMode(Handle);
_ = InitializeWebViewAsync();
}
private async Task InitializeWebViewAsync()
{
try
{
webView = new WebView2
{
Dock = DockStyle.Fill
};
httpController = new HttpController(_httpClient);
Controls.Add(webView);
await webView.EnsureCoreWebView2Async(null);
webView.CoreWebView2.NavigationCompleted += CoreWebView2OnNavigationCompleted;
webView.CoreWebView2.DocumentTitleChanged += CoreWebView2OnDocumentTitleChanged;
webView.CoreWebView2.PermissionRequested += (sender, args) =>
{
args.State = CoreWebView2PermissionState.Allow;
};
webView.CoreWebView2.WebMessageReceived += async (sender, args) =>
{
await HandleWebMessageAsync(args);
};
// Wait for the server to start and get the URL
string? navigationUrl = Program.ServerUrl;
if (!string.IsNullOrEmpty(navigationUrl))
{
webView.CoreWebView2.Navigate(navigationUrl);
}
else
{
// Fallback if server didn't start
string htmlPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "index.html");
if (File.Exists(htmlPath))
{
webView.CoreWebView2.Navigate("file:///" + htmlPath.Replace("\\", "/"));
}
else
{
webView.CoreWebView2.NavigateToString("<h1 style='color:white'>index.html not found!</h1><p style='color:white'>Place it in the same folder as the .exe</p>");
}
}
}
catch (Exception ex)
{
Debug.WriteLine($"Failed to initialize WebView: {ex.Message}");
}
}
private async Task HandleWebMessageAsync(CoreWebView2WebMessageReceivedEventArgs args)
{
try
{
var message = JsonSerializer.Deserialize<JsonElement>(args.WebMessageAsJson);
var messageType = message.GetProperty("type").GetString();
string? requestId = message.TryGetProperty("requestId", out var reqIdProp) ? reqIdProp.GetString() : null;
if (string.IsNullOrEmpty(requestId))
requestId = Guid.NewGuid().ToString();
switch (messageType)
{
case MSG_HTTP_REQUEST:
await HandleHttpRequestAsync(message, requestId);
break;
case MSG_BRWS_RELOAD:
await HandleBrwsReload();
break;
case MSG_PWSH_NEW:
await HandlePwshNewAsync(message, requestId);
break;
case MSG_PWSH_INPUT:
await HandlePwshInputAsync(message, requestId);
break;
case MSG_PWSH_KILL:
await HandlePwshKillAsync(requestId);
break;
case MSG_PWSH_STOP:
await HandlePwshStopAsync(requestId);
break;
case MSG_FILE_WRITE:
await HandleFileWriteAsync(message, requestId);
break;
case MSG_FILE_READ:
await HandleFileReadAsync(message, requestId);
break;
case MSG_FILE_TEXT_SEARCH:
await HandleFileTextSearch(message, requestId);
break;
case MSG_SYS_INFO:
await HandleSystemInfo(requestId);
break;
case MSG_RAW_TO_MD:
await HandleRawToMarkdownAsync(message, requestId);
break;
default:
PostErrorMessage("Unrecognized message type");
break;
}
}
catch (Exception ex)
{
Debug.WriteLine($"Error handling web message: {ex.Message}");
PostErrorMessage($"Error processing request: {ex.Message}");
}
}
private async Task HandleHttpRequestAsync(JsonElement message, string requestId)
{
var result = await httpController!.SendHttpRequest(message, requestId);
webView.CoreWebView2.PostWebMessageAsJson(JsonSerializer.Serialize(result, JsonOptions));
}
private async Task HandleBrwsReload()
{
try
{
List<PwshProcess> processesToDispose;
lock (_processListLock)
{
processesToDispose = processList.ToList();
}
foreach (var process in processesToDispose)
{
try
{
process.Dispose();
}
catch (Exception ex)
{
Debug.WriteLine($"Error disposing process {process.RequestId}: {ex.Message}");
}
}
processList = new ConcurrentBag<PwshProcess>();
await webView.CoreWebView2.CallDevToolsProtocolMethodAsync("Network.clearBrowserCache", "{}");
webView.CoreWebView2.Reload();
}
catch (Exception ex)
{
Debug.WriteLine($"Error reloading browser: {ex.Message}");
PostErrorMessage($"Error reloading browser: {ex.Message}");
}
}
private async Task HandlePwshNewAsync(JsonElement message, string requestId)
{
try
{
string name = message.GetProperty("name").GetString();
if (string.IsNullOrWhiteSpace(name))
name = "New window";
bool keepOpen = message.GetProperty("keepOpen").GetBoolean();
bool asyncOutput = message.TryGetProperty("asyncOutput", out var asyncProp) ? asyncProp.GetBoolean() : false;
PwshProcess newWindow = new PwshProcess(requestId, name, keepOpen, asyncOutput)
{
Type = MSG_TYPE_PWSH_RESULT
};
processList.Add(newWindow);
EnsureAsyncOutputTaskRunning();
PostWebMessage(new PwshResult(requestId)
{
Type = MSG_TYPE_PWSH_RESULT,
Status = 0,
Output = "Pwsh started successfully",
IsRunning = newWindow.IsRunning
});
}
catch (Exception ex)
{
PostWebMessage(new PwshResult(requestId)
{
Type = MSG_TYPE_PWSH_RESULT,
Status = 1,
Output = $"Failed to start PowerShell: {ex.Message}"
});
}
}
private async Task HandlePwshInputAsync(JsonElement message, string requestId)
{
try
{
string command = message.GetProperty("command").GetString();
if (string.IsNullOrWhiteSpace(command))
throw new ArgumentException("Command cannot be empty");
var inputProcess = GetProcessByRequestId(requestId);
if (inputProcess == null)
{
PwshProcess newWindow = new PwshProcess(requestId, "window-" + requestId, false, false)
{
Type = MSG_TYPE_PWSH_RESULT
};
try
{
newWindow.ExecuteCommand(command);
string output = newWindow.GetAllOutput();
PostWebMessage(new PwshResult(requestId)
{
Type = MSG_TYPE_PWSH_RESULT,
Status = 0,
Output = output,
IsRunning = newWindow.IsRunning
});
}
finally
{
newWindow.Dispose();
}
}
else
{
inputProcess.ExecuteCommand(command);
PostWebMessage(new PwshResult(requestId)
{
Type = MSG_TYPE_PWSH_RESULT,
Status = 0,
IsRunning = inputProcess.IsRunning,
Output = "Running command"
});
}
}
catch (Exception ex)
{
PostWebMessage(new PwshResult(requestId)
{
Type = MSG_TYPE_PWSH_RESULT,
Status = 1,
Output = ex.Message
});
}
}
private async Task HandlePwshKillAsync(string requestId)
{
try
{
var processToKill = GetProcessByRequestId(requestId);
if (processToKill == null)
{
PostWebMessage(new PwshResult(requestId)
{
Type = MSG_TYPE_PWSH_RESULT,
Status = 1,
Output = "Pwsh process not found or already stopped"
});
}
else
{
processToKill.Dispose();
PostWebMessage(new PwshResult(requestId)
{
Type = MSG_TYPE_PWSH_RESULT,
Status = 0,
Output = "Pwsh process killed successfully"
});
}
}
catch (Exception ex)
{
PostWebMessage(new PwshResult(requestId)
{
Type = MSG_TYPE_PWSH_RESULT,
Status = 1,
Output = $"Error killing process: {ex.Message}"
});
}
}
private async Task HandlePwshStopAsync(string requestId)
{
try
{
var processToStop = GetProcessByRequestId(requestId);
if (processToStop == null)
{
PostWebMessage(new PwshResult(requestId)
{
Type = MSG_TYPE_PWSH_RESULT,
Status = 1,
Output = "Pwsh process not found or already stopped"
});
}
else
{
processToStop.StopCommand();
PostWebMessage(new PwshResult(requestId)
{
Type = MSG_TYPE_PWSH_RESULT,
Status = 0,
Output = "Command stopped successfully",
IsRunning = processToStop.IsRunning
});
}
}
catch (Exception ex)
{
PostWebMessage(new PwshResult(requestId)
{
Type = MSG_TYPE_PWSH_RESULT,
Status = 1,
Output = $"Error stopping command: {ex.Message}"
});
}
}
private async Task HandleFileWriteAsync(JsonElement message, string requestId)
{
try
{
string filePath = message.GetProperty("filePath").GetString() ?? string.Empty;
string content = message.GetProperty("content").GetString() ?? string.Empty;
filePath = Helper.GetActualPath(filePath);
if (string.IsNullOrEmpty(filePath))
{
PostWebMessage(new PwshResult(requestId)
{
Type = MSG_FILE_WRITE,
Status = 1,
Output = "Invalid file path"
});
return;
}
await File.WriteAllTextAsync(filePath, content);
PostWebMessage(new PwshResult(requestId)
{
Type = MSG_FILE_WRITE,
Status = 0,
Output = "File written successfully"
});
}
catch (Exception ex)
{
PostWebMessage(new PwshResult(requestId)
{
Type = MSG_FILE_WRITE,
Status = 1,
Output = $"Error writing file: {ex.Message}"
});
}
}
private async Task HandleFileReadAsync(JsonElement element, string requestId)
{
try
{
string filePath = element.GetProperty("filePath").GetString() ?? string.Empty;
filePath = Helper.GetActualPath(filePath);
if (!Helper.IsFileText(filePath))
{
PostWebMessage(new PwshResult(requestId)
{
Type = MSG_FILE_READ,
Status = 1,
Output = "File is not a text file"
});
return;
}
string content = File.ReadAllText(filePath);
PostWebMessage(new PwshResult(requestId)
{
Type = MSG_FILE_READ,
Status = 0,
Output = content
});
}
catch (Exception ex)
{
PostWebMessage(new PwshResult(requestId)
{
Type = MSG_FILE_READ,
Status = 1,
Output = $"Error reading file: {ex.Message}"
});
}
}
private async Task HandleFileTextSearch(JsonElement message, string requestId)
{
try
{
string filePath = message.GetProperty("filePath").GetString() ?? string.Empty;
string searchText = message.GetProperty("searchText").GetString() ?? string.Empty;
filePath = Helper.GetActualPath(filePath);
if (string.IsNullOrEmpty(searchText) || !Helper.IsFileText(filePath))
{
PostWebMessage(new PwshResult(requestId)
{
Type = MSG_FILE_TEXT_SEARCH,
Status = 1,
Output = "Invalid search text or file is not a text file"
});
return;
}
string content = File.ReadAllText(filePath);
string lowerContent = content.ToLower();
string lowerSearchText = searchText.ToLower();
var lines = content.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None);
var matches = new List<object>();
int charPosition = 0;
for (int lineNumber = 0; lineNumber < lines.Length; lineNumber++)
{
string line = lines[lineNumber];
int lineStartPosition = charPosition;
int columnPosition = 0;
while ((columnPosition = line.ToLower().IndexOf(lowerSearchText, columnPosition)) != -1)
{
matches.Add(new
{
line = lineNumber + 1,
column = columnPosition + 1,
matchText = line.Substring(columnPosition, searchText.Length)
});
columnPosition += searchText.Length;
}
charPosition += line.Length + 1; // +1 for line ending
}
if (matches.Count == 0)
{
PostWebMessage(new PwshResult(requestId)
{
Type = MSG_FILE_TEXT_SEARCH,
Status = 0,
Output = JsonSerializer.Serialize(new { found = false, matches = new object[] { } }, JsonOptions)
});
}
else
{
PostWebMessage(new PwshResult(requestId)
{
Type = MSG_FILE_TEXT_SEARCH,
Status = 0,
Output = JsonSerializer.Serialize(new { found = true, matchCount = matches.Count, matches = matches }, JsonOptions)
});
}
}
catch (Exception ex)
{
PostWebMessage(new PwshResult(requestId)
{
Type = MSG_FILE_TEXT_SEARCH,
Status = 1,
Output = $"Error searching text in file: {ex.Message}"
});
}
}
private async Task HandleSystemInfo( string requestId)
{
try
{
var sysInfo = SystemMonitorController.GetFullMetricsJson();
PostWebMessage(new PwshResult(requestId)
{
Type = MSG_SYS_INFO,
Status = 0,
Output = sysInfo
});
}
catch (Exception ex)
{
PostWebMessage(new PwshResult(requestId)
{
Type = MSG_SYS_INFO,
Status = 1,
Output = $"Error fetching system info: {ex.Message}"
});
}
}
private async Task HandleRawToMarkdownAsync(JsonElement message, string requestId)
{
try
{
string text = message.GetProperty("text").GetString() ?? string.Empty;
LlmContentController contentController = new LlmContentController();
string markdown = await contentController.ProcessToMarkdown(Encoding.UTF8.GetBytes(text));
PostWebMessage(new PwshResult(requestId)
{
Type = MSG_RAW_TO_MD,
Status = 0,
Output = markdown
});
}
catch (Exception ex)
{
PostWebMessage(new PwshResult(requestId)
{
Type = MSG_RAW_TO_MD,
Status = 1,
Output = $"Error converting text to markdown: {ex.Message}"
});
}
}
private PwshProcess? GetProcessByRequestId(string requestId)
{
lock (_processListLock)
{
return processList.FirstOrDefault(p => p.RequestId == requestId && p.IsRunning);
}
}
private void PostWebMessage<T>(T message) where T : class
{
try
{
webView?.CoreWebView2?.PostWebMessageAsJson(JsonSerializer.Serialize(message, JsonOptions));
}
catch (Exception ex)
{
Debug.WriteLine($"Error posting web message: {ex.Message}");
}
}
private void PostErrorMessage(string message)
{
try
{
webView?.CoreWebView2?.PostWebMessageAsJson(JsonSerializer.Serialize(
new { type = MSG_TYPE_ERROR, message = message },
JsonOptions));
}
catch (Exception ex)
{
Debug.WriteLine($"Error posting error message: {ex.Message}");
}
}
private void EnsureAsyncOutputTaskRunning()
{
if (_asyncOutputTask == null || _asyncOutputTask.IsCompleted)
{
_asyncOutputCts = new CancellationTokenSource();
_asyncOutputTask = StartAsyncOutputPollingAsync(_asyncOutputCts.Token);
}
}
private async Task StartAsyncOutputPollingAsync(CancellationToken cancellationToken)
{
const int pollingIntervalMs = 500;
try
{
while (!cancellationToken.IsCancellationRequested)
{
List<PwshProcess> asyncProcesses;
lock (_processListLock)
{
asyncProcesses = processList.Where(p => p.AsyncOutput && p.IsRunning).ToList();
}
foreach (var process in asyncProcesses)
{
try
{
string output = process.GetIncrementalOutput();
if (!string.IsNullOrEmpty(output))
{
PostWebMessage(new PwshResult(process.RequestId)
{
Type = MSG_PWSH_ASYNC_OUTPUT,
Status = 0,
Output = output,
IsRunning = process.IsRunning
});
}
}
catch (Exception ex)
{
Debug.WriteLine($"Error getting async output from process {process.RequestId}: {ex.Message}");
}
}
// Remove processos que não estão mais rodando e não têm keepOpen
lock (_processListLock)
{
var processesToRemove = processList.Where(p => !p.IsRunning && !p.Keep).ToList();
foreach (var process in processesToRemove)
{
var items = processList.ToList();
items.Remove(process);
processList = new ConcurrentBag<PwshProcess>(items);
}
}
await Task.Delay(pollingIntervalMs, cancellationToken);
}
}
catch (OperationCanceledException)
{
// Esperado quando a task é cancelada
}
catch (Exception ex)
{
Debug.WriteLine($"Unexpected error in async output polling: {ex.Message}");
}
}
protected override void OnFormClosing(FormClosingEventArgs e)
{
try
{
_asyncOutputCts?.Cancel();
if (_asyncOutputTask != null && !_asyncOutputTask.IsCompleted)
{
if (!_asyncOutputTask.Wait(TimeSpan.FromSeconds(2)))
{
Debug.WriteLine("Async output task did not complete within timeout");
}
}
List<PwshProcess> processesToDispose;
lock (_processListLock)
{
processesToDispose = processList.ToList();
}
foreach (var process in processesToDispose)
{
try
{
process.Dispose();
}
catch (Exception ex)
{
Debug.WriteLine($"Error disposing process {process.RequestId}: {ex.Message}");
}
}
processList = new ConcurrentBag<PwshProcess>();
}
catch (Exception ex)
{
Debug.WriteLine($"Error in OnFormClosing: {ex.Message}");
}
finally
{
base.OnFormClosing(e);
}
}
private void CoreWebView2OnDocumentTitleChanged(object? sender, object e)
{
try
{
if (webView?.CoreWebView2 == null)
return;
var title = webView.CoreWebView2.DocumentTitle;
if (!string.IsNullOrWhiteSpace(title))
Text = title;
}
catch (Exception ex)
{
Debug.WriteLine($"Error updating document title: {ex.Message}");
}
}
private async void CoreWebView2OnNavigationCompleted(object? sender, CoreWebView2NavigationCompletedEventArgs e)
{
if (!e.IsSuccess)
return;
await UpdateTitleAndFaviconAsync();
}
private async Task UpdateTitleAndFaviconAsync()
{
try
{
if (webView?.CoreWebView2 == null)
return;
var title = await webView.ExecuteScriptAsync("document.title");
var parsedTitle = Helper.ParseJsString(title);
if (!string.IsNullOrWhiteSpace(parsedTitle))
Text = parsedTitle;
var faviconHrefJson = await webView.ExecuteScriptAsync(@"(() => {
const rels = ['icon','shortcut icon','apple-touch-icon','mask-icon'];
for (const rel of rels) {
const el = document.querySelector(`link[rel~='${rel.split(' ')[0]}']`) || document.querySelector(`link[rel='${rel}']`);
if (el && el.href) return el.href;
}
const any = document.querySelector('link[rel*=icon]');
if (any && any.href) return any.href;
return new URL('/favicon.ico', location.href).href;
})()");
var faviconHref = Helper.ParseJsString(faviconHrefJson);
if (string.IsNullOrWhiteSpace(faviconHref))
return;
var icon = await TitleBarController.TryLoadIconFromUrlAsync(faviconHref, _httpClient);
if (icon is not null)
Icon = icon;
}
catch (Exception ex)
{
Debug.WriteLine($"Error updating title and favicon: {ex.Message}");
}
}
}
}