-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainform.cs
More file actions
2141 lines (1887 loc) · 73.7 KB
/
Copy pathMainform.cs
File metadata and controls
2141 lines (1887 loc) · 73.7 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 Microsoft.Web.WebView2.WinForms;
using Microsoft.Web.WebView2.Core;
using Microsoft.Win32;
using System;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Net.Http;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using WindowsInput;
using WindowsInput.Native;
namespace Wrok
{
public partial class MainForm : Form
{
// Shared HttpClient instance for all network checks/requests.
private static readonly HttpClient _httpClient = new HttpClient();
// UI controls and resources.
private WebView2? webView;
private NotifyIcon? trayIcon;
private ContextMenuStrip? trayMenu;
private ToolStripMenuItem? macrosMenu;
// Base URL and entries used for the tray menu.
private readonly string baseUrl = "https://grok.com/";
private readonly (string name, string url)[] menuPages = new[]
{
(Properties.Resources.Settings, "?_s=home"),
};
// Global hotkey identifiers and modifier flags.
private const int HOTKEY_ID = 0x9000;
private const int WM_HOTKEY = 0x0312;
private const uint MOD_CONTROL = 0x0002;
private const uint MOD_SHIFT = 0x0004;
[DllImport("user32.dll", SetLastError = true)]
private static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk);
[DllImport("user32.dll", SetLastError = true)]
private static extern bool UnregisterHotKey(IntPtr hWnd, int id);
// Inactivity timer for automatic minimization.
private System.Windows.Forms.Timer? inactivityTimer;
private TimeSpan inactivityTimeout = TimeSpan.FromSeconds(30);
private ActivityMessageFilter? activityFilter;
private bool inactivityEnabled = true;
private readonly int[] inactivityOptions = new[] { 0, 30, 60, 90 };
// Fields used for activity tracking.
private DateTime _lastActivity = DateTime.UtcNow;
private readonly object _activityLock = new object();
// Input simulator and hotkey base IDs for macros.
private InputSimulator? _inputSimulator;
// Separate base for macro hotkeys to avoid collisions with other IDs.
private const int HOTKEY_BASE = 0x9100;
private const int HOTKEY_MACRO_1 = HOTKEY_BASE + 0;
private const int HOTKEY_MACRO_2 = HOTKEY_BASE + 1;
private const int HOTKEY_MACRO_3 = HOTKEY_BASE + 2;
private const int HOTKEY_MACRO_4 = HOTKEY_BASE + 3;
private const int HOTKEY_MACRO_5 = HOTKEY_BASE + 4;
// P/Invoke SetForegroundWindow to ensure the app can bring itself forward.
[DllImport("user32.dll", SetLastError = true)]
private static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern short VkKeyScan(char ch);
public MainForm()
{
InitializeComponent();
// Install a global message filter (weak reference) to detect user activity.
activityFilter = new ActivityMessageFilter(this);
try
{
Application.AddMessageFilter(activityFilter);
}
catch
{
activityFilter = null; // Not critical if registration fails.
}
// Initialize tray icon and apply current theme.
InitializeTrayIcon();
RefreshTheme();
LoadWindowSettings();
// Check first-run state via a marker file in %LOCALAPPDATA%\Wrok.
var markerDir = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"Wrok");
var firstRunMarker = Path.Combine(markerDir, "firstrun.marker");
var savedSeconds = Properties.Settings.Default.InactivityTimeoutSeconds;
bool isFirstRun = false;
try
{
if (!Directory.Exists(markerDir))
Directory.CreateDirectory(markerDir);
isFirstRun = !File.Exists(firstRunMarker);
}
catch
{
isFirstRun = false;
}
if (isFirstRun || savedSeconds <= 0)
{
// Disable inactivity timer on first run or if setting is non-positive.
inactivityTimeout = TimeSpan.Zero;
inactivityEnabled = false;
Properties.Settings.Default.InactivityTimeoutSeconds = 0;
Properties.Settings.Default.Save();
try
{
File.WriteAllText(firstRunMarker, DateTime.UtcNow.ToString("o"));
}
catch
{
// Ignore write errors for the marker file.
}
}
else
{
inactivityTimeout = TimeSpan.FromSeconds(savedSeconds);
inactivityEnabled = savedSeconds > 0;
}
_ = InitializeWebViewAsync();
InitializeInactivityTimer();
// Load page in background without bringing window to front.
try
{
_ = LoadUrlAsync(baseUrl, bringToFront: false);
}
catch
{
// Non-fatal.
}
// Save window state events.
this.Resize += MainForm_Resize;
this.ResizeEnd += MainForm_ResizeEnd;
this.Move += MainForm_Move;
// Update tray menu to reflect inactivity settings.
UpdateTrayMenuInactivityState();
}
private void InitializeComponent()
{
var version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
this.Text = version != null ? $"Wrok {version.Major}.{version.Minor}.{version.Build}" : "Wrok";
this.WindowState = FormWindowState.Normal;
this.StartPosition = FormStartPosition.CenterScreen;
this.FormBorderStyle = FormBorderStyle.Sizable;
this.ShowInTaskbar = false;
this.Visible = false;
}
// Load stored window position/size; if valid, apply it.
private void LoadWindowSettings()
{
var s = Properties.Settings.Default;
// Log loaded values for debugging (use Output window)
try
{
Trace.WriteLine($"LoadWindowSettings: WindowLeft={s.WindowLeft}, WindowTop={s.WindowTop}, WindowWidth={s.WindowWidth}, WindowHeight={s.WindowHeight}, IsMaximized={s.IsMaximized}");
}
catch { }
// Determine if size and position look valid.
bool hasValidSize = (s.WindowWidth > 0 && s.WindowHeight > 0);
// Treat (0,0) as "not set" to avoid unintentionally placing window at top-left.
bool hasExplicitPosition = (s.WindowLeft != 0 || s.WindowTop != 0);
if (hasValidSize && hasExplicitPosition)
{
this.StartPosition = FormStartPosition.Manual;
var desired = new Rectangle(
s.WindowLeft,
s.WindowTop,
s.WindowWidth,
s.WindowHeight);
bool intersects = false;
foreach (var scr in Screen.AllScreens)
{
if (scr.WorkingArea.IntersectsWith(desired))
{
intersects = true;
break;
}
}
if (intersects)
{
this.Bounds = desired;
}
else
{
// Stored position is off-screen: use stored size but center on a screen.
this.Size = new Size(s.WindowWidth, s.WindowHeight);
this.StartPosition = FormStartPosition.CenterScreen;
try { this.CenterToScreen(); } catch { }
Trace.WriteLine("LoadWindowSettings: Stored bounds are off-screen; using stored size and CenterScreen.");
}
}
else if (hasValidSize && !hasExplicitPosition)
{
// Size is known but position not explicitly set -> apply size and center the window.
this.Size = new Size(s.WindowWidth, s.WindowHeight);
this.StartPosition = FormStartPosition.CenterScreen;
try { this.CenterToScreen(); } catch { }
Trace.WriteLine("LoadWindowSettings: Position not set (0,0); applied stored size and using CenterScreen.");
}
else
{
// No valid stored size -> keep default StartPosition (CenterScreen from InitializeComponent).
Trace.WriteLine("LoadWindowSettings: No valid stored size; keeping default StartPosition.");
}
if (s.IsMaximized)
{
this.WindowState = FormWindowState.Maximized;
}
}
// Save current window geometry into user-scoped settings.
private void SaveWindowSettings()
{
try
{
var s = Properties.Settings.Default;
Rectangle bounds;
if (this.WindowState == FormWindowState.Maximized || this.WindowState == FormWindowState.Minimized)
bounds = this.RestoreBounds;
else
bounds = this.Bounds;
s.WindowLeft = bounds.Left;
s.WindowTop = bounds.Top;
s.WindowWidth = Math.Max(100, bounds.Width);
s.WindowHeight = Math.Max(100, bounds.Height);
s.IsMaximized = (this.WindowState == FormWindowState.Maximized);
s.Save();
}
catch
{
// Swallow errors — saving window state is non-critical.
}
}
private void MainForm_Resize(object? sender, EventArgs e)
{
if (this.WindowState == FormWindowState.Minimized || this.WindowState == FormWindowState.Maximized)
{
SaveWindowSettings();
}
}
private void MainForm_ResizeEnd(object? sender, EventArgs e)
{
if (this.WindowState == FormWindowState.Normal)
{
SaveWindowSettings();
}
}
private void MainForm_Move(object? sender, EventArgs e)
{
if (this.WindowState == FormWindowState.Normal)
{
SaveWindowSettings();
}
}
/// <summary>
/// Initialize WebView2 and inject helper script for focus/text insertion and activity events.
/// </summary>
private async Task InitializeWebViewAsync()
{
webView = new WebView2
{
Dock = DockStyle.Fill
};
this.Controls.Add(webView);
string userDataPath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"Wrok",
"WebView2Data");
try
{
Directory.CreateDirectory(userDataPath);
}
catch
{
// Non-fatal if creating folder fails.
}
webView.CoreWebView2InitializationCompleted += async (s, e) =>
{
if (webView.CoreWebView2 != null)
{
// JavaScript helper injected into each document to:
// - reset activity on user interactions inside the webview
// - reliably focus editable elements (including contenteditable editors)
// - insert text and optionally trigger a send/submit action
var helperScript = @"
(function() {
const resetActivity = function() { window.chrome.webview.postMessage('resetActivity'); };
['mousemove','mousedown','keydown','scroll','touchstart'].forEach(function(ev){ window.addEventListener(ev, resetActivity, { passive: true }); });
function isProseMirror(el) {
try {
if (!el || !el.className) return false;
var cn = (el.className + '').toString().toLowerCase();
return cn.indexOf('prosemirror') !== -1 || cn.indexOf('tiptap') !== -1;
} catch(e) { return false; }
}
function tryFocusInput(el) {
try {
el.focus();
if ('setSelectionRange' in el && typeof el.setSelectionRange === 'function') {
var len = (el.value || '').length;
try { el.setSelectionRange(len, len); } catch(e) {}
}
try { el.dispatchEvent(new Event('input', { bubbles: true })); } catch(e) {}
try { el.dispatchEvent(new Event('focus', { bubbles: true })); } catch(e) {}
try { el.scrollIntoView({ block: 'nearest', inline: 'nearest' }); } catch(e) {}
return true;
} catch(e) { return false; }
}
function placeCaretAtEndContentEditable(el) {
try {
el.focus();
var sel = window.getSelection();
var range = document.createRange();
// place caret at the end of the element
range.selectNodeContents(el);
range.collapse(false);
sel.removeAllRanges();
sel.addRange(range);
try { el.dispatchEvent(new InputEvent('input', { bubbles: true })); } catch(e) {}
try { el.dispatchEvent(new Event('focus', { bubbles: true })); } catch(e) {}
try { el.dispatchEvent(new MouseEvent('mousedown', { bubbles: true, cancelable: true })); } catch(e) {}
try { el.dispatchEvent(new MouseEvent('mouseup', { bubbles: true, cancelable: true })); } catch(e) {}
try { el.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true })); } catch(e) {}
try { el.scrollIntoView({ block: 'nearest', inline: 'nearest' }); } catch(e) {}
return true;
} catch(e) { return false; }
}
window.__wrokEnsureFocus = function() {
try {
var el = document.activeElement;
if (!el || el === document.body || !(el.isContentEditable || 'value' in el)) {
el = document.querySelector('[contenteditable], textarea, input[type=text], input[type=search], [role=textbox]');
}
if (!el) {
// fallback: search common editable targets
el = document.querySelector('textarea, input[type=text], [contenteditable]');
if (!el) return false;
}
var tag = (el.tagName || '').toUpperCase();
// Prefer standard inputs and textareas.
if ((tag === 'INPUT' || tag === 'TEXTAREA' || 'value' in el) && tryFocusInput(el)) return true;
// Handle contenteditable editors.
if (el.isContentEditable && placeCaretAtEndContentEditable(el)) return true;
// Search editable descendants if host element isn't itself editable.
var child = el.querySelector('textarea, input[type=text], [contenteditable]');
if (child) {
if (child.isContentEditable) return placeCaretAtEndContentEditable(child);
return tryFocusInput(child);
}
// Last resort: click host and try again.
try { el.click(); } catch(e) {}
if (el.isContentEditable) return placeCaretAtEndContentEditable(el);
return false;
} catch(e) {
return false;
}
};
window.__wrokSend = function(text, pressEnter) {
try {
if (typeof text !== 'string') text = String(text || '');
var target = document.activeElement;
if (!target || target === document.body || !(target.isContentEditable || 'value' in target)) {
target = document.querySelector('[contenteditable], textarea, input[type=text], input[type=search], [role=textbox]');
}
if (!target) return false;
try { if (window.__wrokEnsureFocus) window.__wrokEnsureFocus(); } catch(e) {}
try { target.focus(); } catch(e) {}
var tag = (target.tagName || '').toUpperCase();
if (tag === 'INPUT' || tag === 'TEXTAREA' || 'value' in target) {
var start = typeof target.selectionStart === 'number' ? target.selectionStart : (target.value || '').length;
var end = typeof target.selectionEnd === 'number' ? target.selectionEnd : start;
var val = target.value || '';
var prefix = (start > 0 && val.charAt(start - 1) !== ' ') ? ' ' : '';
var newVal = val.slice(0, start) + prefix + text + val.slice(end);
target.value = newVal;
var newPos = start + prefix.length + text.length;
try { target.setSelectionRange(newPos, newPos); } catch (e) {}
try { target.dispatchEvent(new Event('input', { bubbles: true })); } catch(e) {}
try { target.dispatchEvent(new Event('change', { bubbles: true })); } catch(e) {}
if (pressEnter) {
try {
if (target.form) {
if (typeof target.form.requestSubmit === 'function') target.form.requestSubmit();
else target.form.submit();
} else {
target.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', code: 'Enter', keyCode: 13, which: 13, bubbles: true }));
target.dispatchEvent(new KeyboardEvent('keyup', { key: 'Enter', code: 'Enter', keyCode: 13, which: 13, bubbles: true }));
}
} catch(e) {}
}
return true;
}
// Handle contenteditable insertion and optional submit.
var sel = window.getSelection();
var range = sel && sel.rangeCount ? sel.getRangeAt(0) : null;
if (!range) {
var prefix = (target.innerText && target.innerText.slice(-1) !== ' ') ? ' ' : '';
target.innerText = (target.innerText || '') + prefix + text;
var r2 = document.createRange();
r2.selectNodeContents(target);
r2.collapse(false);
sel.removeAllRanges();
sel.addRange(r2);
try { target.dispatchEvent(new InputEvent('input', { bubbles: true })); } catch (e) {}
if (pressEnter) {
var btn = document.querySelector('button[type=submit], button[aria-label*=""send"" i], button[class*=""send"" i], [role=button][aria-label*=""send"" i]');
if (btn) { try { btn.click(); } catch (e) {} }
else {
try { target.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', code: 'Enter', keyCode: 13, which: 13, bubbles: true })); } catch (e) {}
try { target.dispatchEvent(new KeyboardEvent('keyup', { key: 'Enter', code: 'Enter', keyCode: 13, which: 13, bubbles: true })); } catch (e) {}
}
}
return true;
}
var prefix = '';
var sc = range.startContainer;
var off = range.startOffset;
var prevChar = '';
if (sc.nodeType === Node.TEXT_NODE) {
if (off > 0) prevChar = sc.textContent.charAt(off - 1) || '';
else {
var prev = sc.previousSibling;
if (prev && prev.nodeType === Node.TEXT_NODE) prevChar = prev.textContent.charAt(prev.textContent.length - 1) || '';
}
} else {
var prevNode = range.startContainer.childNodes[off - 1];
if (prevNode && prevNode.nodeType === Node.TEXT_NODE) prevChar = prevNode.textContent.charAt(prevNode.textContent.length - 1) || '';
}
if (prevChar && prevChar !== ' ') prefix = ' ';
var node = document.createTextNode(prefix + text);
range.insertNode(node);
range.setStartAfter(node);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
try { target.dispatchEvent(new InputEvent('input', { bubbles: true })); } catch (e) {}
if (pressEnter) {
var btn2 = document.querySelector('button[type=submit], button[aria-label*=""send"" i], button[class*=""send"" i], [role=button][aria-label*=""send"" i]');
if (btn2) { try { btn2.click(); } catch (e) {} }
else {
try { range.insertNode(document.createElement('br')); } catch (e) {}
try { range.setStartAfter(node.nextSibling || node); } catch (e) {}
try { range.collapse(true); } catch (e) {}
try { sel.removeAllRanges(); sel.addRange(range); } catch (e) {}
try { target.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', code: 'Enter', keyCode: 13, which: 13, bubbles: true })); } catch (e) {}
try { target.dispatchEvent(new KeyboardEvent('keyup', { key: 'Enter', code: 'Enter', keyCode: 13, which: 13, bubbles: true })); } catch (e) {}
}
}
return true;
} catch (e) {
return false;
}
};
})();";
try
{
await webView.CoreWebView2.AddScriptToExecuteOnDocumentCreatedAsync(helperScript);
}
catch
{
// Ignore script injection failures — non-fatal.
}
// If the page is already loaded, execute the helper immediately to ensure availability.
try
{
await webView.CoreWebView2.ExecuteScriptAsync(helperScript);
}
catch (Exception ex)
{
Trace.WriteLine($"Inject helperScript to current document failed: {ex}");
}
// Listen for messages from the injected script (activity resets).
webView.CoreWebView2.WebMessageReceived += (sender, args) =>
{
if (args.TryGetWebMessageAsString() == "resetActivity")
{
ResetInactivityTimer();
}
};
}
};
try
{
var env = await CoreWebView2Environment.CreateAsync(userDataFolder: userDataPath);
await webView.EnsureCoreWebView2Async(env);
}
catch
{
// Non-fatal if environment creation fails.
}
}
// Perform a quick, low-overhead JS call into the registered helper functions.
private async Task SendTextToWebViewAsync(string text, bool pressEnter = false)
{
if (webView?.CoreWebView2 == null)
return;
// Ensure the WebView has focus on the UI thread.
try
{
if (!this.IsDisposed && this.IsHandleCreated)
{
var tcs = new TaskCompletionSource<bool>();
this.BeginInvoke((MethodInvoker)(() =>
{
try
{
webView?.Focus();
SetForegroundWindow(this.Handle);
}
catch { }
finally { tcs.TrySetResult(true); }
}));
await tcs.Task.ConfigureAwait(false);
}
}
catch { }
// Short delay to allow focus transfer to settle.
await Task.Delay(120).ConfigureAwait(false);
var payload = System.Text.Json.JsonSerializer.Serialize(text);
var callScript = $"(function(){{ try {{ if (window.__wrokEnsureFocus) window.__wrokEnsureFocus(); return window.__wrokSend ? window.__wrokSend({payload}, {(pressEnter ? "true" : "false")}) : false; }} catch(e) {{ return false; }} }})();";
string? rawResult = null;
try
{
rawResult = await webView.CoreWebView2.ExecuteScriptAsync(callScript).ConfigureAwait(false);
Trace.WriteLine(String.Format(Properties.Resources.ParsingClickScriptResultFailed0, rawResult));
}
catch (Exception ex)
{
Trace.WriteLine(String.Format(Properties.Resources.ParsingClickScriptResultFailed0, ex));
}
bool jsSucceeded = false;
try
{
if (!string.IsNullOrWhiteSpace(rawResult))
{
var trimmed = rawResult.Trim();
if (trimmed.Length >= 2 && trimmed[0] == '"' && trimmed[^1] == '"')
trimmed = trimmed.Substring(1, trimmed.Length - 2);
if (string.Equals(trimmed, "true", StringComparison.OrdinalIgnoreCase))
jsSucceeded = true;
else
{
try
{
var el = System.Text.Json.JsonSerializer.Deserialize<System.Text.Json.JsonElement>(rawResult);
if (el.ValueKind == System.Text.Json.JsonValueKind.True) jsSucceeded = true;
else if (el.ValueKind == System.Text.Json.JsonValueKind.Object && el.TryGetProperty("ok", out var p) && p.ValueKind == System.Text.Json.JsonValueKind.True) jsSucceeded = true;
}
catch { }
}
}
}
catch (Exception ex)
{
Trace.WriteLine(String.Format(Properties.Resources.ParsingClickScriptResultFailed0, ex));
}
// If Enter is requested, try clicking a visible send button as a robust approach.
if (pressEnter)
{
// Small delay to allow UI changes (button enablement) to complete.
await Task.Delay(140).ConfigureAwait(false);
var clickScript = @"
(function(){
try {
var sel = 'button[type=submit], button[aria-label*=""send"" i], button[aria-label*=""submit"" i], button[aria-label*=""absenden"" i], button[class*=""send"" i], [role=button][aria-label*=""send"" i]';
var btn = document.querySelector(sel);
if (!btn) {
// fallback: search visible buttons by text/label
var candidates = Array.from(document.querySelectorAll('button, [role=button]'));
for (var i=0;i<candidates.length;i++){
try {
var txt = ((candidates[i].innerText || candidates[i].getAttribute('aria-label') || candidates[i].title) + '').toLowerCase();
if (txt.indexOf('absend') !== -1 || txt.indexOf('send') !== -1 || txt.indexOf('submit') !== -1) { btn = candidates[i]; break; }
} catch(e){}
}
}
if (!btn) return false;
try {
var wasDisabled = !!btn.disabled;
if (wasDisabled) { btn.disabled = false; btn.removeAttribute('disabled'); }
btn.click();
if (wasDisabled) { setTimeout(function(){ try { btn.disabled = true; btn.setAttribute('disabled',''); } catch(e){} }, 200); }
return true;
} catch(e){ return false; }
} catch(e){ return false; }
})();";
string? clickResult = null;
try
{
clickResult = await webView.CoreWebView2.ExecuteScriptAsync(clickScript).ConfigureAwait(false);
Trace.WriteLine(String.Format(Properties.Resources.SendTextToWebViewAsyncClickScriptResult0, clickResult));
}
catch (Exception ex)
{
Trace.WriteLine(String.Format(Properties.Resources.ParsingClickScriptResultFailed0, ex));
}
bool clickSucceeded = false;
try
{
if (!string.IsNullOrWhiteSpace(clickResult))
{
var t = clickResult.Trim();
if (t.Length >= 2 && t[0] == '"' && t[^1] == '"') t = t.Substring(1, t.Length - 2);
clickSucceeded = string.Equals(t, "true", StringComparison.OrdinalIgnoreCase);
}
}
catch (Exception ex)
{
Trace.WriteLine(String.Format(Properties.Resources.ParsingClickScriptResultFailed0, ex));
}
if (clickSucceeded)
{
Trace.WriteLine(Properties.Resources.SendTextToWebViewAsyncClickSucceededReturning);
return;
}
// If JS inserted text but click failed, send an actual OS Enter keystroke as fallback.
// Many editor frameworks ignore synthetic KeyboardEvent dispatch from JS.
if (jsSucceeded)
{
Trace.WriteLine("JS inserted text but click failed — sending Enter via InputSimulator fallback.");
try
{
// Ensure focus on UI thread.
try
{
if (!this.IsDisposed && this.IsHandleCreated)
{
this.BeginInvoke((MethodInvoker)(() =>
{
try
{
webView?.Focus();
SetForegroundWindow(this.Handle);
}
catch { }
}));
}
}
catch { }
await Task.Delay(80).ConfigureAwait(false);
_inputSimulator?.Keyboard.KeyPress(VirtualKeyCode.RETURN);
Trace.WriteLine("SendTextToWebViewAsync: Enter sent via InputSimulator after JS insert.");
return;
}
catch (Exception ex)
{
Trace.WriteLine($"Enter fallback via InputSimulator failed: {ex}");
// Continue to full fallback below.
}
}
}
else
{
if (jsSucceeded)
return;
}
// Full fallback: type text via InputSimulator and optionally press Enter.
try
{
// Ensure focus on UI thread.
try
{
if (!this.IsDisposed && this.IsHandleCreated)
{
this.BeginInvoke((MethodInvoker)(() =>
{
try
{
webView?.Focus();
SetForegroundWindow(this.Handle);
}
catch { }
}));
}
}
catch { }
await Task.Delay(150).ConfigureAwait(false);
if (!string.IsNullOrEmpty(text))
{
_inputSimulator?.Keyboard.TextEntry(text);
await Task.Delay(40).ConfigureAwait(false);
}
if (pressEnter)
{
_inputSimulator?.Keyboard.KeyPress(VirtualKeyCode.RETURN);
Trace.WriteLine("SendTextToWebViewAsync: fallback Enter sent via InputSimulator.");
}
}
catch (Exception ex)
{
Trace.WriteLine($"Fallback via InputSimulator failed: {ex}");
}
}
// Initialize the tray icon and context menu entries.
private void InitializeTrayIcon()
{
trayMenu = new ContextMenuStrip();
trayMenu.ShowItemToolTips = true;
trayMenu.Items.Add(Properties.Resources.ShowWindow, null, (s, e) => Reactivate());
trayMenu.Items.Add(Properties.Resources.Reload, null, async (s, e) =>
{
try
{
if (webView?.CoreWebView2 != null)
webView.CoreWebView2.Reload();
else
await LoadUrlAsync(baseUrl, bringToFront: false);
}
catch
{
// Non-fatal.
}
});
trayMenu.Items.Add(new ToolStripSeparator());
// Inactivity submenu.
var inactivityMenu = new ToolStripMenuItem(Properties.Resources.Inaktivity);
int current = Properties.Settings.Default.InactivityTimeoutSeconds;
foreach (var sec in inactivityOptions)
{
var item = new ToolStripMenuItem(string.Format(Properties.Resources._0Seconds, sec))
{
Tag = sec,
CheckOnClick = false,
Checked = (current == sec)
};
if (sec == 0)
{
item.Text = string.Format(Properties.Resources._0Deactivated, sec);
}
item.Click += InactivityMenuItem_Click;
inactivityMenu.DropDownItems.Add(item);
}
trayMenu.Items.Add(inactivityMenu);
trayMenu.Items.Add(new ToolStripSeparator());
// Macros menu
InitializeMacrosMenu();
if (macrosMenu != null) trayMenu.Items.Add(macrosMenu);
trayMenu.Items.Add(new ToolStripSeparator());
foreach (var page in menuPages)
{
var item = trayMenu.Items.Add(page.name);
item.Click += async (s, e) => await LoadUrlAsync(baseUrl + page.url);
}
trayMenu.Items.Add(Properties.Resources.ClearCache, null, async (s, e) => await ClearCacheAsync());
trayMenu.Items.Add(new ToolStripSeparator());
trayMenu.Items.Add(Properties.Resources.AboutWrok, null, (s, e) =>
{
using (var dlg = new AboutForm())
{
dlg.ShowDialog(this);
}
});
trayMenu.Items.Add(new ToolStripSeparator()); trayMenu.Items.Add(Properties.Resources.Exit, null, (s, e) => Application.Exit());
var initialIcon = IsDarkMode() ? Properties.Resources.wrok_white : Properties.Resources.wrok_black;
try
{
trayIcon = new NotifyIcon
{
Text = Properties.Resources.WrokClickToOpen,
ContextMenuStrip = trayMenu,
Visible = true,
Icon = (Icon)initialIcon.Clone()
};
}
catch
{
try
{
trayIcon = new NotifyIcon
{
Text = Properties.Resources.WrokClickToOpen,
ContextMenuStrip = trayMenu,
Visible = true,
Icon = initialIcon
};
}
catch
{
// Ignore icon creation errors.
}
}
try
{
this.Icon = (Icon)initialIcon.Clone();
}
catch
{
this.Icon = initialIcon;
}
if (trayIcon != null)
{
trayIcon.MouseClick += (s, e) =>
{
if (e.Button == MouseButtons.Left)
Reactivate();
};
}
UpdateTrayMenuInactivityState();
}
// Show the window and ensure content is loaded if necessary.
private void Reactivate()
{
LoadWindowSettings();
// If using center screen positioning (no saved geometry), center now.
if (this.StartPosition == FormStartPosition.CenterScreen)
{
try { this.CenterToScreen(); } catch { }
}
this.Show();
this.WindowState = Properties.Settings.Default.IsMaximized ? FormWindowState.Maximized : FormWindowState.Normal;
this.Opacity = 1.0;
this.ShowInTaskbar = true;
this.BringToFront();
this.Activate();
ResetInactivityTimer();
try
{
if (webView != null)
{
bool needLoad = false;
if (webView.CoreWebView2 == null)
{
needLoad = true;
}
else
{
try
{
var src = webView.CoreWebView2.Source?.ToString() ?? string.Empty;
if (!src.Contains(baseUrl, StringComparison.OrdinalIgnoreCase))
needLoad = true;
}
catch
{
needLoad = true;
}
}
if (needLoad)
_ = LoadUrlAsync(baseUrl, bringToFront: true);
}
}
catch
{
// Ignore errors during reactivation.
}
}
// Load a URL and optionally bring the window to the front.
private async Task LoadUrlAsync(string url, bool bringToFront = true)
{
try
{
if (webView == null)
return;
if (webView.CoreWebView2 == null)
{
try
{
await webView.EnsureCoreWebView2Async(null);
}
catch
{
}
}
var core = webView.CoreWebView2;
if (core != null)
{
bool online = await HasInternetConnectionAsync(attempts: 3, timeoutSeconds: 5);
if (online)
{
try
{
core.Navigate(url);
}
catch (Exception ex)
{
Log(ex, "core.Navigate failed");
await ShowNoNetImageAsync();
}
}
else
{
await ShowNoNetImageAsync();
}
}
else
{
await ShowNoNetImageAsync();
}
}
catch
{
try