-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathMainForm.cs
More file actions
2088 lines (1815 loc) · 85.1 KB
/
MainForm.cs
File metadata and controls
2088 lines (1815 loc) · 85.1 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.CognitiveServices.Speech;
using Microsoft.CognitiveServices.Speech.Audio;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using NAudio.Wave;
using Whisper.net.Ggml;
using System.Globalization;
using EchoSharp.Abstractions.SpeechTranscription;
using EchoSharp.Abstractions.VoiceActivityDetection;
using EchoSharp.NAudio;
using EchoSharp.SpeechTranscription;
using EchoSharp.WebRtc.WebRtcVadSharp;
using EchoSharp.Whisper.net;
using WebRtcVadSharp;
using System.ComponentModel;
using System.Drawing.Imaging;
using System.Text;
using Newtonsoft.Json;
using SPCHR.Services;
namespace SPCHR
{
public partial class MainForm : Form
{
private bool isListening = false;
private SpeechRecognizer? recognizer;
private readonly IConfiguration configuration;
private PictureBox microphoneIcon;
private IRealtimeSpeechTranscriptor _transcriptor;
private WaveInEvent? _waveIn;
private MicrophoneInputSource _micAudioSource;
private CancellationTokenSource? _transcriptionCancellation;
private string _modelPath;
private GgmlType _modelType = GgmlType.TinyEn;
// OpenAI and Semantic Kernel
private IOpenAIVisionService _openAIService;
private bool _useOpenAiVision = true;
private bool useWhisper = false;
// Auto-insert setting
private bool _autoInsertEnabled = true;
private StringBuilder _accumulatedText = new StringBuilder();
// Public properties to expose current state to SettingsForm
public bool AutoInsertEnabled => _autoInsertEnabled;
public bool VisionAIEnabled => _useOpenAiVision;
[DllImport("user32.dll")]
private static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, UIntPtr dwExtraInfo);
[DllImport("user32.dll")]
private static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk);
[DllImport("user32.dll")]
private static extern bool UnregisterHotKey(IntPtr hWnd, int id);
[DllImport("user32.dll")]
private static extern IntPtr GetFocus();
[DllImport("user32.dll")]
private static extern IntPtr GetAncestor(IntPtr hWnd, uint gaFlags);
[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
private static extern int GetWindowThreadProcessId(IntPtr hWnd, out int lpdwProcessId);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern int GetWindowText(IntPtr hWnd, System.Text.StringBuilder lpString, int nMaxCount);
[DllImport("user32.dll")]
private static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);
[DllImport("user32.dll")]
private static extern IntPtr GetDC(IntPtr hWnd);
[DllImport("gdi32.dll")]
private static extern bool BitBlt(IntPtr hdcDest, int xDest, int yDest, int wDest, int hDest, IntPtr hdcSrc, int xSrc, int ySrc, int rop);
// Add PrintWindow API import near other DLL imports
[DllImport("user32.dll")]
private static extern bool PrintWindow(IntPtr hWnd, IntPtr hdcBlt, uint nFlags);
// Constants for PrintWindow
private const uint PW_CLIENTONLY = 0x00000001;
private const uint PW_RENDERFULLCONTENT = 0x00000002;
// RECT structure
[StructLayout(LayoutKind.Sequential)]
private struct RECT
{
public int left, top, right, bottom;
}
[DllImport("user32.dll")]
private static extern int ReleaseDC(IntPtr hWnd, IntPtr hDc);
// Additional APIs for direct text insertion
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
private static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
private static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, string lParam);
[DllImport("user32.dll")]
private static extern uint SendInput(uint nInputs, INPUT[] pInputs, int cbSize);
[DllImport("user32.dll")]
private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
[DllImport("user32.dll")]
private static extern bool AttachThreadInput(uint idAttach, uint idAttachTo, bool fAttach);
[DllImport("kernel32.dll")]
private static extern uint GetCurrentThreadId();
// Additional method for UI Automation approach
[DllImport("oleacc.dll")]
private static extern int AccessibleObjectFromWindow(IntPtr hwnd, uint dwObjectID, ref Guid riid, out IntPtr ppvObject);
// Constants for UI Automation
private const uint OBJID_CARET = 0xFFFFFFF8;
// Constants for direct text insertion
private const uint EM_REPLACESEL = 0x00C2;
private const uint WM_CHAR = 0x0102;
private const uint INPUT_KEYBOARD = 1;
private const uint KEYEVENTF_UNICODE = 0x0004;
// INPUT structure for SendInput
[StructLayout(LayoutKind.Sequential)]
private struct INPUT
{
public uint type;
public KEYBDINPUT ki;
}
[StructLayout(LayoutKind.Sequential)]
private struct KEYBDINPUT
{
public ushort wVk;
public ushort wScan;
public uint dwFlags;
public uint time;
public IntPtr dwExtraInfo;
}
private const int SRCCOPY = 0x00CC0020; // BitBlt raster operation code
private const uint GA_ROOT = 2; // Retrieves the top-level window
// Modifiers for hotkeys
private const uint MOD_ALT = 0x0001;
private const uint MOD_CONTROL = 0x0002;
private const uint MOD_SHIFT = 0x0004;
private const int HOTKEY_ID = 1;
private const int HOTKEY_ID_AUTO_INSERT = 2;
private const int HOTKEY_ID_VISION_AI = 3;
// Dynamic hotkey settings
private uint _hotkeyModifiers = MOD_CONTROL | MOD_ALT;
private uint _hotkeyVirtualKey = 0x4C; // Default to L key
// Auto-insert toggle hotkey settings
private uint _hotkeyAutoInsertModifiers = MOD_CONTROL | MOD_ALT;
private uint _hotkeyAutoInsertVirtualKey = 0x49; // Default to I key
// Vision AI toggle hotkey settings
private uint _hotkeyVisionAIModifiers = MOD_CONTROL | MOD_ALT;
private uint _hotkeyVisionAIVirtualKey = 0x56; // Default to V key
private const uint KEYEVENTF_KEYUP = 0x0002;
private const byte VK_CONTROL = 0x11;
private const byte VK_V = 0x56;
private bool _modelDownloaded = false;
private Label _downloadStatusLabel;
private CheckBox openAICheckBox;
private string _screenshotPath;
// VAD-triggered screenshot coordination
private string _currentSegmentScreenshotPath = string.Empty;
private bool _screenshotTakenForCurrentSegment = false; // Track if screenshot was taken for current segment
// Sentence accumulation for complete utterance processing
private StringBuilder _pendingSentence = new StringBuilder();
private string _pendingScreenshotPath = string.Empty;
private System.Windows.Forms.Timer _sentenceDebounceTimer;
private const int SENTENCE_DEBOUNCE_MS = 1500; // Wait 1.5 seconds of silence before processing
private readonly object _sentenceLock = new object();
// Semaphore to prevent concurrent text insertion operations
private static readonly SemaphoreSlim _textInsertionSemaphore = new SemaphoreSlim(1, 1);
// Debug logging
private static readonly string _debugLogPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"debug_log_{DateTime.Now:yyyy-MM-dd_HH-mm-ss}.txt");
private static readonly object _logLock = new object();
public MainForm()
{
// Initialize debug logging
ClearDebugLog();
WriteDebugLog("=== SPCHR Application Started ===");
WriteDebugLog($"Debug log location: {_debugLogPath}");
configuration = new ConfigurationBuilder()
.SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
.AddJsonFile("appsettings.json")
.AddJsonFile("appsettings.Development.json", optional: true)
.Build();
// Initialize OpenAI settings
_openAIService = new OpenAIVisionService(configuration["OpenAI:ApiKey"], configuration["OpenAI:Model"] ?? "o4-mini", configuration["OpenAI:Endpoint"] ?? "https://api.openai.com/");
if (string.IsNullOrEmpty(_openAIService.ApiKey))
{
_useOpenAiVision = false; // Disable OpenAI if no API key
}
// Load AutoInsert setting
_autoInsertEnabled = true; // default value
if (bool.TryParse(configuration["AutoInsertEnabled"], out bool autoInsertValue))
{
_autoInsertEnabled = autoInsertValue;
}
InitializeComponent(); // This needs to happen before we access any controls
// Update form properties
this.FormBorderStyle = FormBorderStyle.FixedSingle;
this.TopMost = true;
this.ShowInTaskbar = true;
this.MinimizeBox = true;
this.MaximizeBox = false;
this.ControlBox = true;
this.StartPosition = FormStartPosition.Manual;
//Rectangle workingArea = Screen.GetWorkingArea(this);
//this.Location = new Point(
// workingArea.Right - this.Width - 20,
// workingArea.Top + 20
//);
trayIcon = new NotifyIcon()
{
Icon = this.Icon,
Visible = true
};
// Add context menu to tray icon
var contextMenu = new ContextMenuStrip();
var settingsMenuItem = new ToolStripMenuItem("Settings");
settingsMenuItem.Click += SettingsMenuItem_Click;
contextMenu.Items.Add(settingsMenuItem);
contextMenu.Items.Add(new ToolStripSeparator());
var hotkeyInfoMenuItem = new ToolStripMenuItem("Hotkey: Loading...");
hotkeyInfoMenuItem.Enabled = false;
contextMenu.Items.Add(hotkeyInfoMenuItem);
var exitMenuItem = new ToolStripMenuItem("Exit");
exitMenuItem.Click += (s, e) =>
{
// Ensure proper cleanup before exiting
DisposeTrayIcon();
Application.Exit();
};
contextMenu.Items.Add(exitMenuItem);
trayIcon.ContextMenuStrip = contextMenu;
InitializeMicrophoneIcon();
LoadHotkeySettings();
RegisterGlobalHotKey();
InitializeSpeechRecognizer();
InitializeSentenceDebounceTimer();
// Add OpenAI Checkbox (after InitializeComponent has been called)
this.openAICheckBox = new CheckBox();
this.openAICheckBox.AutoSize = true;
this.openAICheckBox.Location = new Point(80,70);
this.openAICheckBox.Name = "openAICheckBox";
this.openAICheckBox.Size = new Size(180, 19);
this.openAICheckBox.TabIndex = 3;
this.openAICheckBox.Text = "Enable Vision AI";
this.openAICheckBox.UseVisualStyleBackColor = true;
this.openAICheckBox.Checked = _useOpenAiVision;
this.openAICheckBox.CheckedChanged += new EventHandler(this.openAICheckBox_CheckedChanged);
this.openAICheckBox.Enabled = !string.IsNullOrEmpty(_openAIService.ApiKey);
// Add the checkbox to controls
this.Controls.Add(this.openAICheckBox);
}
private void MainForm_Resize(object sender, EventArgs e)
{
if (this.WindowState == FormWindowState.Minimized)
{
this.Hide(); // Hide the form when minimized
trayIcon.Visible = true;
}
}
protected override void OnClosing(CancelEventArgs e)
{
// Properly dispose of the tray icon when closing the form
DisposeTrayIcon();
base.OnClosing(e);
}
private void InitializeSentenceDebounceTimer()
{
_sentenceDebounceTimer = new System.Windows.Forms.Timer();
_sentenceDebounceTimer.Interval = SENTENCE_DEBOUNCE_MS;
_sentenceDebounceTimer.Tick += SentenceDebounceTimer_Tick;
}
private async void SentenceDebounceTimer_Tick(object sender, EventArgs e)
{
_sentenceDebounceTimer.Stop();
string completeSentence;
string screenshotPath;
lock (_sentenceLock)
{
completeSentence = _pendingSentence.ToString().Trim();
screenshotPath = _pendingScreenshotPath;
_pendingSentence.Clear();
_pendingScreenshotPath = string.Empty;
}
if (!string.IsNullOrEmpty(completeSentence))
{
WriteDebugLog($"=== DEBOUNCE COMPLETE - Processing accumulated sentence ===");
WriteDebugLog($"Complete sentence: '{completeSentence}' (Length: {completeSentence.Length})");
await ProcessResults(completeSentence, screenshotPath);
}
}
private void AccumulateRecognizedText(string text, string screenshotPath)
{
lock (_sentenceLock)
{
// Capture the screenshot path from the first segment if not already set
if (string.IsNullOrEmpty(_pendingScreenshotPath) && !string.IsNullOrEmpty(screenshotPath))
{
_pendingScreenshotPath = screenshotPath;
WriteDebugLog($"Captured screenshot path for sentence: {screenshotPath}");
}
// Accumulate the text
if (_pendingSentence.Length > 0 && !text.StartsWith(" "))
{
_pendingSentence.Append(" ");
}
_pendingSentence.Append(text.Trim());
WriteDebugLog($"Accumulated text: '{_pendingSentence}' (added: '{text.Trim()}')");
}
// Reset the debounce timer - wait for more text or timeout
_sentenceDebounceTimer.Stop();
_sentenceDebounceTimer.Start();
}
private void LogMicrophoneDevice(string context)
{
try
{
if (WaveInEvent.DeviceCount > 0)
{
var capabilities = WaveInEvent.GetCapabilities(0);
WriteDebugLog($"{context} using microphone: {capabilities.ProductName}");
Console.WriteLine($"{context} using microphone: {capabilities.ProductName}");
}
else
{
WriteDebugLog($"No microphone devices found for {context}");
Console.WriteLine($"No microphone devices found for {context}");
}
}
catch (Exception ex)
{
WriteDebugLog($"Failed to get microphone name for {context}: {ex.Message}");
}
}
private async void InitializeSpeechRecognizer()
{
try
{
var subscriptionKey = configuration["AzureSpeech:SubscriptionKey"];
var region = configuration["AzureSpeech:Region"];
if (string.IsNullOrEmpty(subscriptionKey) || string.IsNullOrEmpty(region))
{
useWhisper = true;
toggleButton.Enabled = false; // Disable until model is downloaded
_modelPath = Path.Combine(Application.StartupPath, "models", $"ggml-{_modelType.ToString().ToLower()}.bin");
await DownloadWhisperModel(_modelType);
await InitializeRealtimeTranscriptor();
return;
}
var config = SpeechConfig.FromSubscription(subscriptionKey, region);
var audioConfig = AudioConfig.FromDefaultMicrophoneInput();
// Log the microphone device name for Azure Speech Services
LogMicrophoneDevice("Azure Speech");
recognizer = new SpeechRecognizer(config, audioConfig);
// Register Recognizing event to capture screenshot when voice activity starts
recognizer.Recognizing += Recognizer_Recognizing;
recognizer.Recognized += Recognizer_Recognized;
}
catch (Exception ex)
{
useWhisper = true;
toggleButton.Enabled = false; // Disable until model is downloaded
_modelPath = Path.Combine(Application.StartupPath, "models", $"ggml-{_modelType.ToString().ToLower()}.bin");
await DownloadWhisperModel(_modelType);
await InitializeRealtimeTranscriptor();
MessageBox.Show($"Falling back to local Whisper model: {ex.Message}");
}
}
private void Recognizer_Recognizing(object? sender, SpeechRecognitionEventArgs e)
{
// Capture screenshot when voice activity is first detected (new segment starts)
if (e.Result.Reason == ResultReason.RecognizingSpeech)
{
// Capture screenshot when voice activity is first detected (new segment starts)
// Recognizing events fire multiple times for the same segment, so we only capture once
// Set flag immediately to prevent race condition with rapid events
if (!_screenshotTakenForCurrentSegment)
{
_screenshotTakenForCurrentSegment = true; // Set immediately to prevent duplicates
WriteDebugLog($"=== NEW VOICE SEGMENT DETECTED (Azure) - Capturing screenshot ===");
// Capture screenshot when voice activity starts
this.Invoke(new Action(() =>
{
_currentSegmentScreenshotPath = TakeScreenshotOfParentWindow();
WriteDebugLog($"Screenshot captured for segment: {_currentSegmentScreenshotPath}");
}));
}
}
}
private void Recognizer_Recognized(object? sender, SpeechRecognitionEventArgs e)
{
if (e.Result.Reason == ResultReason.RecognizedSpeech)
{
string recognizedText = e.Result.Text;
if (!string.IsNullOrEmpty(recognizedText))
{
Console.Write(recognizedText);
WriteDebugLog($"Recognized text: '{recognizedText}' (Length: {recognizedText.Length})");
// Use the screenshot captured when this segment started
string screenshotPath = _currentSegmentScreenshotPath;
// Accumulate text instead of processing immediately
// This handles cases where Azure splits sentences
this.Invoke(new Action(() =>
{
AccumulateRecognizedText(recognizedText, screenshotPath);
}));
// Reset for next segment
_currentSegmentScreenshotPath = string.Empty;
_screenshotTakenForCurrentSegment = false;
}
}
}
private async Task PasteText(string text)
{
try
{
if (string.IsNullOrEmpty(text))
{
WriteDebugLog("Cannot paste empty text");
return;
}
// Save current clipboard content
string originalClipboard = null;
bool hadClipboardContent = false;
try
{
if (Clipboard.ContainsText())
{
originalClipboard = Clipboard.GetText();
hadClipboardContent = true;
}
}
catch (Exception ex)
{
WriteDebugLog($"Warning: Could not read current clipboard content: {ex.Message}");
}
GetTopLevelParentWindow(); // This now gets and sets focus to the appropriate window
// Set the text to clipboard
Clipboard.SetText(text);
// Small delay to ensure clipboard is ready
await Task.Delay(50);
// Simulate Ctrl+V
keybd_event(VK_CONTROL, 0, 0, UIntPtr.Zero);
keybd_event(VK_V, 0, 0, UIntPtr.Zero);
keybd_event(VK_V, 0, (uint)KEYEVENTF_KEYUP, UIntPtr.Zero);
keybd_event(VK_CONTROL, 0, (uint)KEYEVENTF_KEYUP, UIntPtr.Zero);
// Wait for paste operation to complete before restoring clipboard
await Task.Delay(100);
// Restore original clipboard content
if (hadClipboardContent && originalClipboard != null)
{
try
{
Clipboard.SetText(originalClipboard);
}
catch (Exception ex)
{
WriteDebugLog($"Warning: Could not restore original clipboard content: {ex.Message}");
}
}
}
catch (Exception ex)
{
WriteDebugLog($"Error pasting text: {ex.Message}");
}
}
/// <summary>
/// Alternative text insertion method that bypasses clipboard and directly inserts text
/// at the current cursor position using Windows API
/// </summary>
private async Task InsertTextDirect(string text)
{
// Prevent concurrent text insertion operations
if (!await _textInsertionSemaphore.WaitAsync(100)) // 100ms timeout
{
WriteDebugLog("Text insertion already in progress - skipping duplicate request");
return;
}
try
{
if (string.IsNullOrEmpty(text))
{
WriteDebugLog("Cannot insert empty text");
return;
}
// Get the foreground window (where the cursor is)
IntPtr foregroundWindow = GetForegroundWindow();
if (foregroundWindow == IntPtr.Zero)
{
WriteDebugLog("No foreground window found");
return;
}
// Get window title for debugging
var windowTitle = new System.Text.StringBuilder(256);
GetWindowText(foregroundWindow, windowTitle, windowTitle.Capacity);
WriteDebugLog($"Target window: '{windowTitle}' (Handle: {foregroundWindow})");
WriteDebugLog($"Text to insert: '{text}' (Length: {text.Length})");
// Check if running as administrator (affects SendInput)
bool isAdmin = IsRunningAsAdministrator();
WriteDebugLog($"Running as administrator: {isAdmin}");
if (!isAdmin)
{
WriteDebugLog("WARNING: Not running as administrator - SendInput may fail due to UIPI (User Interface Privilege Isolation)");
WriteDebugLog("SUGGESTION: For better compatibility, right-click the executable and select 'Run as administrator'");
}
// Try multiple methods in order of preference
bool success = false;
// Special handling for applications that use custom controls
string windowTitleStr = windowTitle.ToString();
WriteDebugLog($"Detected {windowTitleStr} - using simulated typing method");
success = InsertWithSimulatedTyping(text);
if (success)
{
WriteDebugLog("Text inserted using simulated typing");
return;
}
WriteDebugLog($"{windowTitleStr} simulated typing failed, trying other methods");
// Fallback to clipboard method as last resort - must be on UI thread
await Task.Run(() => this.Invoke(async () => await PasteText(text)));
}
catch (Exception ex)
{
WriteDebugLog($"Error in direct text insertion: {ex.Message}");
WriteDebugLog($"Stack trace: {ex.StackTrace}");
}
finally
{
_textInsertionSemaphore.Release();
}
}
/// <summary>
/// Write debug message to log file with timestamp
/// </summary>
private static void WriteDebugLog(string message)
{
try
{
lock (_logLock)
{
string timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
string logEntry = $"[{timestamp}] {message}";
// Also write to Debug output for development
System.Diagnostics.Debug.WriteLine(logEntry);
// Write to file
File.AppendAllText(_debugLogPath, logEntry + Environment.NewLine);
}
}
catch (Exception ex)
{
// Fallback to Debug output only if file writing fails
System.Diagnostics.Debug.WriteLine($"Failed to write to debug log: {ex.Message}");
System.Diagnostics.Debug.WriteLine($"Original message: {message}");
}
}
/// <summary>
/// Clear the debug log file
/// </summary>
private static void ClearDebugLog()
{
try
{
lock (_logLock)
{
if (File.Exists(_debugLogPath))
{
File.Delete(_debugLogPath);
}
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"Failed to clear debug log: {ex.Message}");
}
}
/// <summary>
/// Check if the application is running as administrator
/// </summary>
private bool IsRunningAsAdministrator()
{
try
{
var identity = System.Security.Principal.WindowsIdentity.GetCurrent();
var principal = new System.Security.Principal.WindowsPrincipal(identity);
return principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator);
}
catch
{
return false;
}
}
/// <summary>
/// Simulated typing method using keybd_event - works without admin privileges
/// </summary>
private bool InsertWithSimulatedTyping(string text)
{
try
{
WriteDebugLog($" - Using simulated typing for {text.Length} characters");
// Save original clipboard content once at the beginning
string originalClipboard = null;
bool hadClipboard = false;
try
{
if (Clipboard.ContainsText())
{
originalClipboard = Clipboard.GetText();
hadClipboard = true;
WriteDebugLog($" - Saved original clipboard content ({originalClipboard?.Length ?? 0} chars)");
}
}
catch (Exception ex)
{
WriteDebugLog($" - Warning: Could not save clipboard content: {ex.Message}");
}
try
{
// Set the entire text to clipboard once
Clipboard.SetText(text);
WriteDebugLog($" - Set text to clipboard");
Thread.Sleep(100); // Give clipboard time to update
// Verify clipboard content was set correctly
string clipboardCheck = Clipboard.GetText();
if (clipboardCheck != text)
{
WriteDebugLog($" - WARNING: Clipboard verification failed. Expected {text.Length} chars, got {clipboardCheck?.Length ?? 0} chars");
}
// Paste the text once
keybd_event(VK_CONTROL, 0, 0, UIntPtr.Zero);
keybd_event(VK_V, 0, 0, UIntPtr.Zero);
keybd_event(VK_V, 0, (uint)KEYEVENTF_KEYUP, UIntPtr.Zero);
keybd_event(VK_CONTROL, 0, (uint)KEYEVENTF_KEYUP, UIntPtr.Zero);
WriteDebugLog($" - Executed paste command");
// Wait longer for Word to process the paste operation
// Word can be slow, especially with longer text
int waitTime = Math.Min(500, text.Length * 2); // 2ms per character, max 500ms
Thread.Sleep(waitTime);
WriteDebugLog($" - Waited {waitTime}ms for paste to complete");
WriteDebugLog($" - Simulated typing: {text.Length}/{text.Length} characters processed");
return true;
}
finally
{
// Add additional delay before restoring clipboard to ensure paste is completely done
Thread.Sleep(200);
WriteDebugLog($" - Additional 200ms delay before clipboard restoration");
// Restore original clipboard content
try
{
if (hadClipboard && originalClipboard != null)
{
Clipboard.SetText(originalClipboard);
WriteDebugLog($" - Restored original clipboard content ({originalClipboard.Length} chars)");
}
else
{
Clipboard.Clear();
WriteDebugLog($" - Cleared clipboard");
}
// Verify the restoration worked
string finalClipboard = Clipboard.GetText();
if (hadClipboard && originalClipboard != null)
{
if (finalClipboard == originalClipboard)
{
WriteDebugLog($" - Clipboard restoration verified successfully");
}
else
{
WriteDebugLog($" - WARNING: Clipboard restoration verification failed");
}
}
}
catch (Exception ex)
{
WriteDebugLog($" - Warning: Could not restore clipboard: {ex.Message}");
}
}
}
catch (Exception ex)
{
WriteDebugLog($" - Simulated typing method failed: {ex.Message}");
return false;
}
}
/// <summary>
/// Open the debug log file in the default text editor
/// </summary>
public void OpenDebugLog()
{
try
{
if (File.Exists(_debugLogPath))
{
System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo
{
FileName = _debugLogPath,
UseShellExecute = true
});
}
else
{
MessageBox.Show($"Debug log file not found at: {_debugLogPath}",
"Debug Log", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (Exception ex)
{
MessageBox.Show($"Could not open debug log: {ex.Message}",
"Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private nint GetTopLevelParentWindow()
{
// First try to get the current foreground window
IntPtr foregroundWindow = GetForegroundWindow();
// Try to get text from the window for diagnostic purposes
var windowTitle = new System.Text.StringBuilder(256);
if (GetWindowText(foregroundWindow, windowTitle, windowTitle.Capacity) > 0)
{
WriteDebugLog($"Foreground window title: {windowTitle}");
}
if (foregroundWindow != IntPtr.Zero)
{
WriteDebugLog($"Foreground window handle: {foregroundWindow}");
// Get the process ID of the foreground window
GetWindowThreadProcessId(foregroundWindow, out int processId);
WriteDebugLog($"Foreground window process ID: {processId}");
return foregroundWindow;
}
// Fall back to GetFocus if GetForegroundWindow failed
IntPtr focusedHandle = GetFocus();
if (focusedHandle == IntPtr.Zero)
{
WriteDebugLog("No control is currently focused.");
return focusedHandle;
}
IntPtr topLevelParent = GetAncestor(focusedHandle, GA_ROOT);
if (topLevelParent != IntPtr.Zero)
{
WriteDebugLog($"Top-level parent window handle: {topLevelParent}");
}
else
{
WriteDebugLog("Failed to retrieve top-level parent window.");
}
return topLevelParent;
}
private void LoadHotkeySettings()
{
try
{
// Load hotkey settings from configuration
string modifiersString = configuration["Hotkey:Modifiers"] ?? "Control,Alt";
string keyString = configuration["Hotkey:Key"] ?? "L";
// Parse modifiers
_hotkeyModifiers = 0;
string[] modifiers = modifiersString.Split(',');
foreach (string modifier in modifiers)
{
switch (modifier.Trim())
{
case "Control":
_hotkeyModifiers |= MOD_CONTROL;
break;
case "Alt":
_hotkeyModifiers |= MOD_ALT;
break;
case "Shift":
_hotkeyModifiers |= MOD_SHIFT;
break;
}
}
// Parse key - convert from Keys enum to virtual key code
if (Enum.TryParse<Keys>(keyString, out Keys key))
{
_hotkeyVirtualKey = (uint)key;
}
else
{
_hotkeyVirtualKey = 0x4C; // Default to L key
}
// Load Auto-Insert hotkey settings
string autoInsertModifiersString = configuration["HotkeyAutoInsert:Modifiers"] ?? "Control,Alt";
string autoInsertKeyString = configuration["HotkeyAutoInsert:Key"] ?? "I";
_hotkeyAutoInsertModifiers = 0;
string[] autoInsertModifiers = autoInsertModifiersString.Split(',');
foreach (string modifier in autoInsertModifiers)
{
switch (modifier.Trim())
{
case "Control":
_hotkeyAutoInsertModifiers |= MOD_CONTROL;
break;
case "Alt":
_hotkeyAutoInsertModifiers |= MOD_ALT;
break;
case "Shift":
_hotkeyAutoInsertModifiers |= MOD_SHIFT;
break;
}
}
if (Enum.TryParse<Keys>(autoInsertKeyString, out Keys autoInsertKey))
{
_hotkeyAutoInsertVirtualKey = (uint)autoInsertKey;
}
else
{
_hotkeyAutoInsertVirtualKey = 0x49; // Default to I key
}
// Load Vision AI hotkey settings
string visionAIModifiersString = configuration["HotkeyVisionAI:Modifiers"] ?? "Control,Alt";
string visionAIKeyString = configuration["HotkeyVisionAI:Key"] ?? "V";
_hotkeyVisionAIModifiers = 0;
string[] visionAIModifiers = visionAIModifiersString.Split(',');
foreach (string modifier in visionAIModifiers)
{
switch (modifier.Trim())
{
case "Control":
_hotkeyVisionAIModifiers |= MOD_CONTROL;
break;
case "Alt":
_hotkeyVisionAIModifiers |= MOD_ALT;
break;
case "Shift":
_hotkeyVisionAIModifiers |= MOD_SHIFT;
break;
}
}
if (Enum.TryParse<Keys>(visionAIKeyString, out Keys visionAIKey))
{
_hotkeyVisionAIVirtualKey = (uint)visionAIKey;
}
else
{
_hotkeyVisionAIVirtualKey = 0x56; // Default to V key
}
}
catch (Exception ex)
{
WriteDebugLog($"Error loading hotkey settings: {ex.Message}");
// Use defaults if loading fails
_hotkeyModifiers = MOD_CONTROL | MOD_ALT;
_hotkeyVirtualKey = 0x4C;
_hotkeyAutoInsertModifiers = MOD_CONTROL | MOD_ALT;
_hotkeyAutoInsertVirtualKey = 0x49;
_hotkeyVisionAIModifiers = MOD_CONTROL | MOD_ALT;
_hotkeyVisionAIVirtualKey = 0x56;
}
}
private void RegisterGlobalHotKey()
{
try
{
bool allSuccessful = true;
// Register main listening toggle hotkey
if (!RegisterHotKey(this.Handle, HOTKEY_ID, _hotkeyModifiers, _hotkeyVirtualKey))
{
string hotkeyDescription = GetHotkeyDescription(_hotkeyModifiers, _hotkeyVirtualKey);
MessageBox.Show($"Could not register hotkey {hotkeyDescription} for Toggle Listening. It may be in use by another application.",
"Hotkey Registration Failed", MessageBoxButtons.OK, MessageBoxIcon.Warning);
allSuccessful = false;
}
// Register Auto-Insert toggle hotkey
if (!RegisterHotKey(this.Handle, HOTKEY_ID_AUTO_INSERT, _hotkeyAutoInsertModifiers, _hotkeyAutoInsertVirtualKey))
{
string hotkeyDescription = GetHotkeyDescription(_hotkeyAutoInsertModifiers, _hotkeyAutoInsertVirtualKey);
MessageBox.Show($"Could not register hotkey {hotkeyDescription} for Toggle Auto-Insert. It may be in use by another application.",