-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNaturalLanguageInterpreter.cs
More file actions
2460 lines (2337 loc) · 135 KB
/
NaturalLanguageInterpreter.cs
File metadata and controls
2460 lines (2337 loc) · 135 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 System;
using System.IO;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text.Json;
using System.Text.RegularExpressions;
using WindowsInput;
using WindowsInput.Native;
using NaturalCommands.Helpers;
using OpenAI;
using OpenAI.Chat;
using OpenAI.Models;
using NaturalCommands;
using NaturalCommands.Models;
namespace NaturalCommands
{
// Win32 API imports and constants for window style and class name
internal static class Win32Api
{
public const int GWL_STYLE = -16;
public const int WS_MAXIMIZEBOX = 0x00010000;
[System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true)]
public static extern int GetWindowLong(IntPtr hWnd, int nIndex);
[System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
public static extern int GetClassName(IntPtr hWnd, System.Text.StringBuilder lpClassName, int nMaxCount);
}
// IMPORTANT: This class is already too large. Do NOT add new methods here.
// Any new functionality should be implemented in a new class and referenced as needed.
// Please refactor existing logic into smaller, focused classes where possible.
public class NaturalLanguageInterpreter
// Action type for Visual Studio command execution
{
/// <summary>
/// Checks if Visual Studio is the active window.
/// </summary>
public static bool IsVisualStudioActive()
{
var procName = NaturalCommands.CurrentApplicationHelper.GetCurrentProcessName();
return procName == "devenv";
}
/// <summary>
/// Ensures the directory for the log file exists.
/// </summary>
// Expanded app mapping for natural language launching
private static readonly Dictionary<string, string> AppMappings = new(StringComparer.OrdinalIgnoreCase)
{
{ "calculator", "calc.exe" },
{ "calc", "calc.exe" },
{ "notepad", "notepad.exe" },
{ "edge", "msedge.exe" },
{ "microsoft edge", "msedge.exe" },
{ "chrome", "chrome.exe" },
{ "code", "code.exe" },
{ "visual studio", "devenv.exe" },
{ "outlook", "outlook.exe" },
{ "explorer", "explorer.exe" },
{ "word", "winword.exe" },
{ "excel", "excel.exe" },
{ "powerpoint", "powerpnt.exe" },
{ "teams", "Teams.exe" },
{ "onenote", "onenote.exe" },
{ "paint", "mspaint.exe" },
{ "microsoft paint", "mspaint.exe" },
{ "terminal", "wt.exe" },
{ "windows terminal", "wt.exe" },
{ "cmd", "wt.exe" }, // Always prefer Windows Terminal
{ "command prompt", "wt.exe" },
{ "steam", "steam://open/main" },
{ "skype", "skype.exe" },
{ "zoom", "zoom.exe" },
{ "slack", "slack.exe" }
};
/// <summary>
/// Uses OpenAI API to interpret text and return an ActionBase (AI fallback).
/// </summary>
public async System.Threading.Tasks.Task<ActionBase?> InterpretWithAIAsync(string text)
{
// Read API key from environment variable
string? apiKey = Environment.GetEnvironmentVariable("OPENAI_API_KEY");
if (string.IsNullOrWhiteSpace(apiKey))
{
NaturalCommands.Helpers.Logger.LogError("OPENAI_API_KEY environment variable not set.");
return null;
}
// Set default model name
string modelName = "gpt-4.1";
// Read prompt from markdown file
string promptPath = "openai_prompt.md";
string prompt;
try
{
prompt = File.ReadAllText(promptPath);
}
catch (Exception ex)
{
NaturalCommands.Helpers.Logger.LogError($"Failed to read {promptPath}: {ex.Message} Using default prompt.");
prompt = "You are an assistant that interprets natural language commands for Windows automation. Output a JSON object for the closest matching action.";
}
NaturalCommands.Helpers.Logger.LogDebug($"[AI] Fallback triggered for: {text}");
// Write the latest prompt to a separate file (overwrites previous file).
// This is intentionally NOT appended to the normal log file.
WriteLatestPromptFile(prompt, text);
// Do NOT log the prompt anymore
try
{
var chatClient = new ChatClient(modelName, apiKey);
var messages = new List<ChatMessage>
{
new SystemChatMessage(prompt),
new UserChatMessage(text)
};
var completionResult = await chatClient.CompleteChatAsync(messages);
var completion = completionResult.Value;
var message = completion.Content[0].Text;
NaturalCommands.Helpers.Logger.LogDebug($"[AI] Raw response: {message}");
if (!string.IsNullOrWhiteSpace(message))
{
try
{
var json = System.Text.Json.JsonDocument.Parse(message);
var root = json.RootElement;
if (root.TryGetProperty("type", out var typeProp))
{
string type = typeProp.GetString() ?? "";
switch (type)
{
case "MoveWindowAction":
return new MoveWindowAction(
root.GetProperty("Target").GetString() ?? "active",
root.GetProperty("Monitor").GetString() ?? "current",
root.GetProperty("Position").GetString(),
root.TryGetProperty("WidthPercent", out var wp) ? wp.GetInt32() : (int?)null,
root.TryGetProperty("HeightPercent", out var hp) ? hp.GetInt32() : (int?)null
);
case "LaunchAppAction":
// Support both "AppExe" and "AppIdOrPath" field names
string? appExe = null;
if (root.TryGetProperty("AppExe", out var appExeProp))
appExe = appExeProp.GetString();
else if (root.TryGetProperty("AppIdOrPath", out var appIdProp))
appExe = appIdProp.GetString();
return new LaunchAppAction(appExe ?? "");
case "SendKeysAction":
return new SendKeysAction(root.GetProperty("KeysText").GetString() ?? "");
case "OpenFolderAction":
return new OpenFolderAction(root.GetProperty("KnownFolder").GetString() ?? "");
// "SetWindowAlwaysOnTopAction" intentionally not supported: feature disabled.
}
}
}
catch (Exception ex)
{
NaturalCommands.Helpers.Logger.LogError($"Failed to parse OpenAI response: {ex.Message}\nResponse: {message}");
}
}
}
catch (Exception ex)
{
NaturalCommands.Helpers.Logger.LogError($"[AI] OpenAI API call failed: {ex.Message}");
}
return null;
}
// Helper to remove polite modifiers from input
private static string RemovePoliteModifiers(string text)
{
var politeWords = new[] { "please", "could you", "would you", "can you", "may you", "kindly", "will you", "would you kindly" };
foreach (var word in politeWords)
{
text = text.Replace(word, "", StringComparison.InvariantCultureIgnoreCase);
}
return text.Trim();
}
// Word replacement functionality moved to `WordReplacementLoader` helper class.
/// <summary>
/// Writes the latest AI prompt (system prompt + user input) to a separate file.
/// Overwrites any previous content so only the latest prompt is kept.
/// The file is intentionally separate from the normal `app.log`.
/// </summary>
private static void WriteLatestPromptFile(string systemPrompt, string userText)
{
try
{
string latestPath = Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..", "..", "bin", "latest_ai_prompt.md"));
var dir = Path.GetDirectoryName(latestPath);
if (!string.IsNullOrEmpty(dir) && !Directory.Exists(dir))
Directory.CreateDirectory(dir);
var content = $"# System Prompt\n\n{systemPrompt}\n\n# User Input\n\n{userText}\n";
File.WriteAllText(latestPath, content);
}
catch (Exception ex)
{
try { NaturalCommands.Helpers.Logger.LogError($"Failed to write latest AI prompt file: {ex.Message}"); } catch { }
}
}
// Central list of available commands/actions for AI matching
public static readonly List<(string Command, string Description)> AvailableCommands = new()
{
("maximize window", "Maximize the active window"),
("move window to left half", "Move the active window to the left half of the screen"),
("move window to right half", "Move the active window to the right half of the screen"),
("move window to other monitor", "Move the active window to the next monitor"),
("open downloads", "Open the Downloads folder"),
("open documents", "Open the Documents folder"),
("open settings", "Open the application settings"),
("close tab", "Close the current tab in supported applications"),
("send keys", "Send a key sequence to the active window"),
("launch app", "Launch a specified application"),
("focus app", "Focus a specified application window"),
("focus window <name>", "Focus a window by its name (e.g. focus window Zoom)"),
("focus <window name>", "Focus a window by its name (e.g. focus Zoom)"),
("show help", "Show help and available commands"),
("natural dictate", "Open the voice dictation form (speak or type natural language commands)"),
("show letters", "Display letter labels on clickable UI elements for voice-based navigation"),
("identify <target>", "Identify a visual target and click when confident, otherwise show numbered options"),
("id <target>", "Shorthand for identify: identify a visual target (e.g. id telegram)"),
("show candidates", "Show numbered candidates from the latest visual identify command"),
("choose <number>", "Choose a numbered visual target candidate"),
("emoji set <name> <emoji>", "Set an emoji for a named shortcut (e.g. emoji set happy 😀)"),
("emoji <name>", "Insert the configured emoji for the given name"),
("emoji <emoji>", "Insert the given emoji immediately"),
("move <direction>", "Start moving the mouse continuously (e.g. move up, move left, move down right, mouse move left)"),
("mouse move <direction>", "Start moving the mouse continuously (e.g. mouse move up, mouse left)"),
("stop mouse", "Stop mouse movement"),
("stop click", "Stop mouse movement and perform a left click"),
("stop right click", "Stop mouse movement and perform a right click"),
("mouse stop", "Stop mouse movement"),
("faster", "Increase mouse movement speed"),
("slower", "Decrease mouse movement speed"),
("mouse faster", "Increase mouse movement speed"),
("mouse slower", "Decrease mouse movement speed"),
("auto click", "Enable auto-click when mouse is idle (default 2000ms delay)"),
("enable auto click", "Enable auto-click mode"),
("start auto click", "Enable auto-click mode"),
("stop auto click", "Disable auto-click mode"),
("disable auto click", "Disable auto-click mode"),
("auto click off", "Disable auto-click mode"),
("auto click faster", "Increase auto-click speed (shorten delay)"),
("auto click speed up", "Increase auto-click speed (shorten delay)"),
("auto click speedup", "Increase auto-click speed (shorten delay)"),
("auto click slower", "Decrease auto-click speed (lengthen delay)"),
("auto click slow down", "Decrease auto-click speed (lengthen delay)"),
("auto click slowdown", "Decrease auto-click speed (lengthen delay)")
};
// Optional emoji mapping for commands. Map a command phrase to a small emoji
// string that will be displayed next to the command in the 'what can I say' UI.
// Emoji logic moved to EmojiManager.cs. Use EmojiManager.SetCommandEmoji, EmojiManager.GetCommandEmoji, EmojiManager.GetAllEmojiMappings instead.
// File used to persist emoji mappings so they can be added over time.
// Will look for a file next to the executable (copied by the build as content).
private static readonly string EmojiMappingsPath = Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "emoji_mappings.json"));
// Back-compat helper used throughout the file: delegate to centralized Logger
private static void AppendLog(string message)
{
try { NaturalCommands.Helpers.Logger.Log(message.TrimEnd()); } catch { }
}
// Static ctor: load persisted mappings (if any) on first access
static NaturalLanguageInterpreter()
{
// Emoji mappings now loaded by EmojiManager
// Load optional word replacements (e.g., 'closed' -> 'close') to make parsing deterministic
WordReplacementLoader.Load();
// Load user-defined multi-action commands (multi_actions.json)
try { NaturalCommands.Helpers.MultiActionLoader.Load(); } catch { }
// Load Talon phrase catalog for fallback matching
try { NaturalCommands.Helpers.TalonCommandCatalog.EnsureLoaded(); } catch { }
}
// Emoji mapping API now provided by EmojiManager.cs
// Visual Studio specific commands
public static readonly List<(string Command, string Description)> VisualStudioCommands = new()
{
("build the solution", "Build the entire solution"),
("build the project", "Build the current project"),
("start debugging", "Start debugging the startup project"),
("start application", "Start without debugging"),
("stop debugging", "Stop debugging"),
("close tab", "Close the current document tab"),
("format document", "Format the current document"),
("find in files", "Open the Find in Files dialog"),
("go to definition", "Go to definition of symbol"),
("rename symbol", "Rename the selected symbol"),
("show solution explorer", "Focus Solution Explorer"),
("open recent files", "Show recent files"),
};
// Explicit canonical mappings from natural phrases to Visual Studio command canonical names.
// These are preferred over fuzzy-matching exported commands because exported lists may contain
// context-menu entries that are not the canonical top-level commands (which caused failures).
private static readonly Dictionary<string, string> VisualStudioCanonicalMappings = new(StringComparer.OrdinalIgnoreCase)
{
{ "build the solution", "Build.BuildSolution" },
{ "build solution", "Build.BuildSolution" },
{ "build the project", "Build.BuildProject" },
{ "build project", "Build.BuildProject" },
{ "clean solution", "Build.CleanSolution" },
{ "clean the solution", "Build.CleanSolution" },
{ "start debugging", "Debug.Start" },
{ "start application", "Debug.StartWithoutDebugging" },
{ "stop debugging", "Debug.StopDebugging" },
{ "close tab", "Window.CloseDocumentWindow" },
{ "close tool window", "Window.CloseToolWindow" },
{ "close the tool window", "Window.CloseToolWindow" },
{ "close current tool window", "Window.CloseToolWindow" },
{ "format document", "Edit.FormatDocument" },
{ "find in files", "Edit.FindinFiles" },
{ "go to definition", "Edit.GoToDefinition" },
{ "rename symbol", "Refactor.Rename" },
{ "show solution explorer", "View.SolutionExplorer" },
{ "open recent files", "File.RecentFiles" }
};
// Mapping from common tool window captions (as spoken or seen in the UI) to their canonical Visual Studio command names.
// This ensures that natural language like "error list", "output window", etc. will always focus the correct tool window,
// and avoids accidental matches to context menu or non-window commands. This mapping is checked BEFORE any fuzzy or exported command matches.
// To add support for a new tool window, simply add its caption (as spoken or as it appears in Visual Studio) and the corresponding View.* command here.
private static readonly Dictionary<string, string> VisualStudioToolWindowMappings = new(StringComparer.OrdinalIgnoreCase)
{
{ "error list", "View.ErrorList" },
{ "output window", "View.Output" },
{ "output", "View.Output" },
{ "solution explorer", "View.SolutionExplorer" },
{ "team explorer", "View.TeamExplorer" },
{ "task list", "View.TaskList" },
{ "properties window", "View.PropertiesWindow" },
{ "properties", "View.PropertiesWindow" },
{ "class view", "View.ClassView" },
{ "object browser", "View.ObjectBrowser" },
{ "call hierarchy", "View.CallHierarchy" },
{ "bookmark window", "View.BookmarkWindow" },
{ "bookmarks", "View.BookmarkWindow" },
{ "find results", "View.FindResults1" },
{ "find results 1", "View.FindResults1" },
{ "find results 2", "View.FindResults2" },
{ "pending changes", "View.PendingChanges" },
{ "git changes", "View.GitChanges" },
{ "git repository", "View.GitRepository" },
{ "diagnostic tools", "Debug.ShowDiagnosticTools" },
{ "immediate window", "Debug.Immediate" },
{ "immediate", "Debug.Immediate" },
{ "autos window", "Debug.Autos" },
{ "autos", "Debug.Autos" },
{ "locals window", "Debug.Locals" },
{ "locals", "Debug.Locals" },
{ "watch window", "Debug.Watch" },
{ "watch", "Debug.Watch" },
{ "call stack", "Debug.CallStack" },
{ "breakpoints", "Debug.Breakpoints" },
{ "exception settings", "Debug.ExceptionSettings" },
{ "test explorer", "TestExplorer.ShowTestExplorer" },
{ "test window", "TestExplorer.ShowTestExplorer" },
{ "live unit testing window", "TestExplorer.ShowLiveUnitTestingWindow" },
{ "live unit testing", "TestExplorer.ShowLiveUnitTestingWindow" },
{ "solution explorer window", "View.SolutionExplorer" },
{ "output pane", "View.Output" },
{ "task pane", "View.TaskList" },
{ "error pane", "View.ErrorList" },
{ "explorer", "View.SolutionExplorer" },
{ "search results", "View.FindResults1" },
{ "search results 1", "View.FindResults1" },
{ "search results 2", "View.FindResults2" },
{ "pending changes window", "View.PendingChanges" },
{ "git window", "View.GitChanges" },
{ "repository window", "View.GitRepository" },
{ "diagnostics", "Debug.ShowDiagnosticTools" },
{ "breakpoint window", "Debug.Breakpoints" },
{ "exception window", "Debug.ExceptionSettings" },
{ "test", "TestExplorer.ShowTestExplorer" },
{ "tests", "TestExplorer.ShowTestExplorer" }
};
// Popular commands that override any matches
private static readonly Dictionary<string, ActionBase> PopularCommands = new(StringComparer.OrdinalIgnoreCase)
{
{ "debug application", new ExecuteVSCommandAction("Debug.Start") },
{ "run application", new ExecuteVSCommandAction("Debug.StartWithoutDebugging") },
{ "stop application", new ExecuteVSCommandAction("Debug.StopDebugging") },
// Ensure 'focus' always triggers Ctrl+Alt+Tab
{ "focus", new SendKeysAction("ctrl alt tab") },
// Voice dictation trigger: opens the voice dictation form (auto-submit 5s)
// Use TimeoutMs=0 so the dictation form does not auto-submit — waits for manual Submit
{ "dictate", new OpenVoiceDictationFormAction(0) }
};
// VS Code specific commands
public static readonly List<(string Command, string Description)> VSCodeCommands = new()
{
("open file", "Open a file"),
("open folder", "Open a folder"),
("close tab", "Close the current tab"),
("format document", "Format the current document"),
("find in files", "Find in files"),
("go to definition", "Go to definition of symbol"),
("rename symbol", "Rename the selected symbol"),
("show explorer", "Show Explorer"),
("show source control", "Show Source Control"),
("show extensions", "Show Extensions"),
("start debugging", "Start debugging"),
("stop debugging", "Stop debugging"),
};
// Enhanced 'what can I say' logic
public static void ShowAvailableCommands()
{
// If this method shows a dialog for long lists, we set this flag so
// the subsequent ShowHelpAction execution can skip the redundant tray notification.
// This avoids showing the same information twice (dialog + balloon).
// It is reset after the ShowHelpAction is processed.
// Note: internal flag; not exposed publicly.
_suppressNextHelpNotification = false;
string? procName = NaturalCommands.CurrentApplicationHelper.GetCurrentProcessName();
if (procName == "devenv")
{
try
{
var window = new SearchVisualStudioCommandsWPF();
window.ShowDialog();
return;
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show($"Error opening search window: {ex.Message}");
}
}
List<(string Command, string Description)> commands;
string appLabel;
if (procName == "devenv")
{
commands = VisualStudioCommands;
appLabel = "Visual Studio";
}
else if (procName == "code")
{
commands = VSCodeCommands;
appLabel = "VS Code";
}
else if (procName == "windowsterminal" || procName == "WindowsTerminal")
{
// Combine Windows Terminal shortcuts with dotnet CLI commands
commands = new List<(string Command, string Description)>(CommandDefinitions.WindowsTerminalCommands);
// Add a section header for dotnet commands
commands.Add(("--- .NET CLI Commands ---", ""));
commands.AddRange(CommandDefinitions.DotNetCommands.Select(c => (c.Command, c.Description)));
appLabel = "Windows Terminal";
}
else
{
commands = AvailableCommands;
appLabel = "General";
}
// Format command list for display. If an emoji is configured for the command,
// show it before the command text (e.g. "📥 open downloads: Open the Downloads folder").
var lines = commands.Select(c =>
{
var emoji = EmojiManager.GetCommandEmoji(c.Command);
if (!string.IsNullOrEmpty(emoji))
return $"- {emoji} {c.Command}: {c.Description}";
return $"- {c.Command}: {c.Description}";
}).ToList();
lines.Add("- refresh Visual Studio shortcuts: Reload the latest keyboard shortcuts from Visual Studio settings");
string message = $"Available commands:\n\n" + string.Join("\n", lines);
// If command list is long, show in dialog and use notification as pointer
if (lines.Count > 8)
{
try
{
var form = new DictationBoxMSP.AvailableCommandsForm();
form.Text = "Available Commands";
// Show modal so callers don't continue until user closes the list.
form.ShowDialog();
_suppressNextHelpNotification = true;
}
catch (Exception)
{
// Fallback to the original DisplayMessage if the new form fails to open
var dlg = new DictationBoxMSP.DisplayMessage(message, 60000, "Available Commands"); // 60 seconds, custom title
System.Windows.Forms.Application.Run(dlg); // Auto-close after timeout
_suppressNextHelpNotification = true;
}
}
else
{
NaturalCommands.TrayNotificationHelper.ShowNotification($"{appLabel} Commands", string.Join("\n", lines), 7000);
}
// Also log to app.log for reference
AppendLog($"[INFO] {appLabel} Supported Commands:\n{message}\n");
}
// Internal flag used to avoid showing a tray notification when the dialog
// has already presented the available commands to the user.
private static bool _suppressNextHelpNotification = false;
// P/Invoke for MonitorFromWindow
[System.Runtime.InteropServices.DllImport("user32.dll")]
private static extern IntPtr MonitorFromWindow(IntPtr hwnd, uint dwFlags);
// P/Invoke for GetMonitorInfo
[System.Runtime.InteropServices.DllImport("user32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
private static extern bool GetMonitorInfo(IntPtr hMonitor, ref MONITORINFOEX lpmi);
// MONITORINFOEX struct
[System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
public struct MONITORINFOEX
{
public int cbSize;
public RECT rcMonitor;
public RECT rcWork;
public uint dwFlags;
[System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.ByValTStr, SizeConst = 32)]
public string szDevice;
}
[System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential)]
public struct RECT
{
public int Left;
public int Top;
public int Right;
public int Bottom;
}
// Action types are now defined in ActionModels.cs
// P/Invoke for SetWindowPos
[System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true)]
private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);
// P/Invoke for ShowWindow
[System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true)]
private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
// P/Invoke helpers for performing mouse clicks from interpreter
[System.Runtime.InteropServices.DllImport("user32.dll")]
private static extern bool SetCursorPos(int X, int Y);
[System.Runtime.InteropServices.DllImport("user32.dll")]
private static extern bool GetCursorPos(out System.Drawing.Point lpPoint);
[System.Runtime.InteropServices.DllImport("user32.dll")]
private static extern IntPtr WindowFromPoint(System.Drawing.Point Point);
// Test hooks: allow unit tests to inject candidate lists and intercept clicks.
public static System.Func<string, System.Collections.Generic.List<NaturalCommands.Models.VisualTargetCandidate>>? VisualIdentifyCandidatesOverride;
public static System.Action<System.Drawing.Point>? ClickOverride;
[System.Runtime.InteropServices.DllImport("user32.dll")]
private static extern void mouse_event(uint dwFlags, int dx, int dy, uint dwData, int dwExtraInfo);
private const uint MOUSEEVENTF_LEFTDOWN = 0x0002;
private const uint MOUSEEVENTF_LEFTUP = 0x0004;
private const uint MOUSEEVENTF_RIGHTDOWN = 0x0008;
private const uint MOUSEEVENTF_RIGHTUP = 0x0010;
private const uint MOUSEEVENTF_MIDDLEDOWN = 0x0020;
private const uint MOUSEEVENTF_MIDDLEUP = 0x0040;
private static void PerformLeftClickAtPoint(System.Drawing.Point point)
{
if (ClickOverride != null)
{
try { ClickOverride(point); } catch { }
return;
}
System.Drawing.Point previous;
try { GetCursorPos(out previous); } catch { previous = System.Windows.Forms.Cursor.Position; }
try
{
var targetWindow = WindowFromPoint(point);
if (targetWindow != IntPtr.Zero)
{
SetForegroundWindow(targetWindow);
}
}
catch { }
SetCursorPos(point.X, point.Y);
System.Threading.Thread.Sleep(35);
var usedInputSimulator = false;
try
{
var sim = new WindowsInput.InputSimulator();
sim.Mouse.LeftButtonDown();
System.Threading.Thread.Sleep(25);
sim.Mouse.LeftButtonUp();
usedInputSimulator = true;
}
catch { }
if (!usedInputSimulator)
{
mouse_event(MOUSEEVENTF_LEFTDOWN, point.X, point.Y, 0, 0);
System.Threading.Thread.Sleep(25);
mouse_event(MOUSEEVENTF_LEFTUP, point.X, point.Y, 0, 0);
}
System.Threading.Thread.Sleep(70);
try { SetCursorPos(previous.X, previous.Y); } catch { }
}
// InterpretAsync implementation
public System.Threading.Tasks.Task<ActionBase?> InterpretAsync(string text)
{
text = (text ?? string.Empty).ToLowerInvariant().Trim();
// Remove polite modifiers and extra punctuation
text = RemovePoliteModifiers(text);
text = WordReplacementLoader.Apply(text);
text = text.Replace(" ", " ").Replace(".", "").Replace(",", "").Trim();
// Common synonym / misrecognition: accept "quick clips" and "quick links" as "quick clicks"
if (text.IndexOf("quick clips", StringComparison.InvariantCultureIgnoreCase) >= 0)
text = System.Text.RegularExpressions.Regex.Replace(text, @"quick\s+clips", "quick clicks", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
if (text.IndexOf("quick links", StringComparison.InvariantCultureIgnoreCase) >= 0)
text = System.Text.RegularExpressions.Regex.Replace(text, @"quick\s+links", "quick clicks", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// Remove extra words that often appear in these commands
var extraWords = new[] { "of this", "of others", "of other windows", "on top of others", "on top of this" };
foreach (var ew in extraWords) text = text.Replace(ew, "");
text = text.Trim();
AppendLog($"[DEBUG] InterpretAsync normalized input: {text}\n");
// ---- special debug: cloud vision request ----
if (text.StartsWith("cloud vision ", StringComparison.OrdinalIgnoreCase))
{
var phrase = text.Substring("cloud vision ".Length).Trim();
AppendLog($"[DEBUG] InterpretAsync matched CloudVision debug action: {phrase}\n");
return System.Threading.Tasks.Task.FromResult<ActionBase?>(new VisualCloudAction(phrase));
}
if (text.StartsWith("vision ai ", StringComparison.OrdinalIgnoreCase))
{
var phrase = text.Substring("vision ai ".Length).Trim();
AppendLog($"[DEBUG] InterpretAsync matched VisionAI debug action: {phrase}\n");
return System.Threading.Tasks.Task.FromResult<ActionBase?>(new VisualCloudAction(phrase));
}
// Focus window by name: /focus [window name], focus [window name], focus window [name]
string? focusPrefix = null;
if (text.StartsWith("/focus ")) focusPrefix = "/focus ";
else if (text.StartsWith("focus window ")) focusPrefix = "focus window ";
else if (text.StartsWith("focus ")) focusPrefix = "focus ";
if (focusPrefix != null)
{
var windowName = text.Substring(focusPrefix.Length).Trim();
if (!string.IsNullOrEmpty(windowName))
{
AppendLog($"[DEBUG] InterpretAsync matched FocusWindow command: {windowName}\n");
return System.Threading.Tasks.Task.FromResult<ActionBase?>(new NaturalCommands.FocusWindowAction(windowName));
}
}
// Check popular commands override
if (PopularCommands.TryGetValue(text, out var popularAction))
{
AppendLog($"[DEBUG] InterpretAsync matched PopularCommand: {text} -> {popularAction.GetType().Name}\n");
return System.Threading.Tasks.Task.FromResult<ActionBase?>(popularAction);
}
// Handle refresh Visual Studio shortcuts command
if (text.Contains("refresh visual studio shortcuts") || text.Contains("reload visual studio shortcuts") || text.Contains("update visual studio shortcuts"))
{
NaturalCommands.Helpers.VisualStudioShortcutHelper.RefreshShortcuts();
AppendLog("[INFO] Refreshed Visual Studio shortcuts from .vssettings file\n");
NaturalCommands.TrayNotificationHelper.ShowNotification("Shortcuts Refreshed", "Visual Studio keyboard shortcuts have been reloaded.", 5000);
return System.Threading.Tasks.Task.FromResult<ActionBase?>(null);
}
// Handle refresh Talon command catalog
if (text.Contains("refresh talon commands") || text.Contains("reload talon commands") || text.Contains("update talon commands"))
{
return System.Threading.Tasks.Task.FromResult<ActionBase?>(new RefreshTalonCatalogAction());
}
// Explicit help/command list queries
var helpQueriesExact = new[] {
"what can i say", "help", "show commands", "show available commands", "list commands", "show help", "commands list", "available commands"
};
if (helpQueriesExact.Any(q => text.Equals(q, StringComparison.InvariantCultureIgnoreCase)))
{
// ShowAvailableCommands performs the appropriate UI (dialog or notification).
// We return null here so no further ShowHelpAction is executed (avoids duplicate notifications).
ShowAvailableCommands();
AppendLog($"[DEBUG] InterpretAsync matched: ShowAvailableCommands displayed (help query)\n");
return System.Threading.Tasks.Task.FromResult<ActionBase?>(null);
}
// Check for configured multi-action commands (exact match or normalized match)
try
{
if (NaturalCommands.Helpers.MultiActionLoader.Commands.TryGetValue(text, out var multi) ||
NaturalCommands.Helpers.MultiActionLoader.Commands.TryGetValue(NaturalCommands.Helpers.MultiActionLoader.NormalizeKey(text), out multi))
{
AppendLog($"[DEBUG] InterpretAsync matched multi-action command: {multi.Name}\n");
return System.Threading.Tasks.Task.FromResult<ActionBase?>(multi);
}
}
catch { }
// More robust matching for 'always on top'/'float above'/'restore' commands
var alwaysOnTopPatterns = new[] {
"always on top", "on top", "float above", "float this window", "float above other windows",
"make this window float above", "make this window float", "float this window above",
"float window above", "make window float", "make window always on top",
"put this window on top", "put window on top", "make window float above", "put window above",
"float this window above other windows", "float window above other windows", "float window above others",
"float this window above others", "float window above",
"put this window above other windows", "put this window above others", "put window above other windows",
"put window above others", "make this window always on top", "make window always on top"
};
// Restore window (un-maximize)
if ((text.Contains("restore") || text.Contains("unmaximize")) && text.Contains("window"))
{
var action = new MoveWindowAction(
Target: "active",
Monitor: "current",
Position: "center",
WidthPercent: 80,
HeightPercent: 80
);
AppendLog("Window maximized\n");
AppendLog($"[DEBUG] InterpretAsync matched: {action.GetType().Name} (restore window)\n");
return System.Threading.Tasks.Task.FromResult<ActionBase?>(action);
}
bool matchedAlwaysOnTop = false;
foreach (var pattern in alwaysOnTopPatterns)
{
if (text.Contains(pattern))
{
matchedAlwaysOnTop = true;
AppendLog($"[DEBUG] InterpretAsync matched pattern: {pattern}\n");
break;
}
}
// Also match regex variants like 'float.*window.*top' or 'make.*window.*top'
if (!matchedAlwaysOnTop)
{
var regexPatterns = new[] {
"float.*window.*top", "make.*window.*top", "float.*window.*above", "make.*window.*float", "put.*window.*top", "put.*window.*above"
};
foreach (var rx in regexPatterns)
{
if (System.Text.RegularExpressions.Regex.IsMatch(text, rx))
{
matchedAlwaysOnTop = true;
AppendLog($"[DEBUG] InterpretAsync matched regex: {rx}\n");
break;
}
}
// Catch-all: match any phrase containing 'float', 'window', and 'above' in any order
if (!matchedAlwaysOnTop)
{
var words = new[] { "float", "window", "above" };
bool allPresent = words.All(w => text.Contains(w));
if (allPresent)
{
matchedAlwaysOnTop = true;
AppendLog("[DEBUG] InterpretAsync matched catch-all: float/window/above\n");
}
}
}
if (matchedAlwaysOnTop)
{
// The always-on-top feature is disabled because it was causing accidental
// behaviors for users. Log and return null so no action is executed.
AppendLog("[INFO] InterpretAsync: 'always on top' command detected but feature is disabled by configuration.\n");
return System.Threading.Tasks.Task.FromResult<ActionBase?>(null);
}
// Send key sequences
if (text.StartsWith("press "))
{
var keysText = text.Substring(6).Trim();
var action = new SendKeysAction(keysText);
AppendLog($"[DEBUG] InterpretAsync matched: {action.GetType().Name} (send keys)\n");
return System.Threading.Tasks.Task.FromResult<ActionBase?>(action);
}
// Maximize/full screen window
if ((text.Contains("maximize") || text.Contains("full screen")) && text.Contains("window"))
{
var action = new MoveWindowAction(
Target: "active",
Monitor: "current",
Position: "center",
WidthPercent: 100,
HeightPercent: 100
);
NaturalCommands.Helpers.Logger.LogDebug($"InterpretAsync matched: {action.GetType().Name}");
return System.Threading.Tasks.Task.FromResult<ActionBase?>(action);
}
// Move window to other monitor (next)
if ((text.Contains("move") || text.Contains("snap")) && text.Contains("window") && (text.Contains("other monitor") || text.Contains("next monitor") || text.Contains("other screen") || text.Contains("next screen") || text.Contains("my other monitor")))
{
var action = new MoveWindowAction(
Target: "active",
Monitor: "next",
Position: null,
WidthPercent: 0,
HeightPercent: 0
);
NaturalCommands.Helpers.Logger.LogDebug($"InterpretAsync matched: {action.GetType().Name} (next monitor)");
return System.Threading.Tasks.Task.FromResult<ActionBase?>(action);
}
// Move window to left half (robust)
if ((text.Contains("left half") || (text.Contains("left") && text.Contains("half"))) || ((text.Contains("move") || text.Contains("snap")) && text.Contains("window") && text.Contains("left")))
{
var action = new MoveWindowAction(
Target: "active",
Monitor: "current",
Position: "left",
WidthPercent: 50,
HeightPercent: 100
);
NaturalCommands.Helpers.Logger.LogDebug($"InterpretAsync matched: {action.GetType().Name} (left half)");
return System.Threading.Tasks.Task.FromResult<ActionBase?>(action);
}
// Move window to right half (robust)
if ((text.Contains("right half") || (text.Contains("right") && text.Contains("half"))) || ((text.Contains("move") || text.Contains("snap")) && text.Contains("window") && text.Contains("right")))
{
var action = new MoveWindowAction(
Target: "active",
Monitor: "current",
Position: "right",
WidthPercent: 50,
HeightPercent: 100
);
NaturalCommands.Helpers.Logger.LogDebug($"InterpretAsync matched: {action.GetType().Name} (right half)");
return System.Threading.Tasks.Task.FromResult<ActionBase?>(action);
}
// Open My Computer / This PC (robust)
if (text.Contains("open my computer") || text.Contains("open this pc") || text.Contains("open my pc") || (text.Contains("open") && text.Contains("computer")) || (text.Contains("open") && text.Contains("pc")))
{
var action = new OpenFolderAction("MyComputer");
NaturalCommands.Helpers.Logger.LogDebug($"InterpretAsync matched: {action.GetType().Name} (my computer)");
return System.Threading.Tasks.Task.FromResult<ActionBase?>(action);
}
// Open documents folder (robust)
if (text.Contains("open documents") || (text.Contains("open") && text.Contains("document")))
{
var action = new OpenFolderAction("Documents");
NaturalCommands.Helpers.Logger.LogDebug($"InterpretAsync matched: {action.GetType().Name} (documents)");
return System.Threading.Tasks.Task.FromResult<ActionBase?>(action);
}
// Open downloads folder (robust)
if (text.Contains("open downloads") || (text.Contains("open") && text.Contains("download")))
{
var action = new OpenFolderAction("Downloads");
NaturalCommands.Helpers.Logger.LogDebug($"InterpretAsync matched: {action.GetType().Name} (downloads)");
return System.Threading.Tasks.Task.FromResult<ActionBase?>(action);
}
// Open settings explicitly: "open settings", "settings", "show settings"
if (text.Equals("open settings", StringComparison.InvariantCultureIgnoreCase)
|| text.Equals("settings", StringComparison.InvariantCultureIgnoreCase)
|| text.Equals("show settings", StringComparison.InvariantCultureIgnoreCase))
{
var action = new OpenSettingsAction();
AppendLog($"[DEBUG] InterpretAsync matched: {action.GetType().Name} (settings)\n");
return System.Threading.Tasks.Task.FromResult<ActionBase?>(action);
}
// Windows Terminal specific commands
string? wtProcName = NaturalCommands.CurrentApplicationHelper.GetCurrentProcessName();
if (wtProcName == "windowsterminal" || wtProcName == "WindowsTerminal")
{
// First check for Windows Terminal keyboard shortcuts
if (CommandDefinitions.WindowsTerminalShortcuts.TryGetValue(text, out var shortcut))
{
var action = new WindowsTerminalShortcutAction(shortcut, text);
NaturalCommands.Helpers.Logger.LogDebug($"InterpretAsync matched Windows Terminal command: '{text}' -> '{shortcut}'");
return System.Threading.Tasks.Task.FromResult<ActionBase?>(action);
}
// Normalize text for dotnet commands - speech recognition often transcribes "dotnet" as "dot net" or "don't net"
string normalizedDotnetText = text
.Replace("dot net", "dotnet")
.Replace("don't net", "dotnet")
.Replace("dont net", "dotnet")
.Replace("dot-net", "dotnet")
.Replace("dot_net", "dotnet");
// Check for dotnet CLI commands (try both original and normalized text)
if (CommandDefinitions.DotNetCommandMappings.TryGetValue(text, out var dotnetCmd) ||
CommandDefinitions.DotNetCommandMappings.TryGetValue(normalizedDotnetText, out dotnetCmd))
{
var action = new RunTerminalCommandAction(dotnetCmd.TerminalCommand, dotnetCmd.Description);
NaturalCommands.Helpers.Logger.LogDebug($"InterpretAsync matched dotnet command: '{text}' (normalized: '{normalizedDotnetText}') -> '{dotnetCmd.TerminalCommand}'");
return System.Threading.Tasks.Task.FromResult<ActionBase?>(action);
}
}
// Windows Explorer specific commands
if (wtProcName == "explorer")
{
// Check for Windows Explorer shortcuts (includes UI Automation commands with "uia:" prefix)
if (CommandDefinitions.WindowsExplorerShortcuts.TryGetValue(text, out var explorerShortcut))
{
var action = new WindowsExplorerShortcutAction(explorerShortcut, text);
NaturalCommands.Helpers.Logger.LogDebug($"InterpretAsync matched Windows Explorer command: '{text}' -> '{explorerShortcut}'");
return System.Threading.Tasks.Task.FromResult<ActionBase?>(action);
}
}
// Open mapped applications (expanded)
// Use WebsiteNavigator for website navigation commands
if (WebsiteNavigator.TryParseWebsiteCommand(text, out var url))
{
if (!string.IsNullOrWhiteSpace(url))
{
var action = new OpenWebsiteAction(url);
AppendLog($"[DEBUG] InterpretAsync matched: {action.GetType().Name} (website: {url})\n");
return System.Threading.Tasks.Task.FromResult<ActionBase?>(action);
}
}
// Open mapped applications (expanded)
if (text.StartsWith("open "))
{
var appName = text.Substring(5).Trim();
// Normalize app name (remove filler words as whole words only)
appName = Regex.Replace(appName, "\\bthe\\b", "", RegexOptions.IgnoreCase).Trim();
appName = Regex.Replace(appName, "\\bapplication\\b", "", RegexOptions.IgnoreCase).Trim();
appName = Regex.Replace(appName, "\\bapp\\b", "", RegexOptions.IgnoreCase).Trim();
appName = Regex.Replace(appName, "\\s+", " ").Trim();
var fillerTokens = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
"up", "for", "me", "now", "please", "just"
};
var filteredTokens = appName
.Split(' ', StringSplitOptions.RemoveEmptyEntries)
.Where(t => !fillerTokens.Contains(t))
.ToArray();
if (filteredTokens.Length > 0)
{
appName = string.Join(" ", filteredTokens);
}
// Strip vendor prefixes like "microsoft " or "ms " to handle phrases such as "microsoft paint"
if (appName.StartsWith("microsoft ", StringComparison.OrdinalIgnoreCase))
appName = appName.Substring("microsoft ".Length).Trim();
else if (appName.StartsWith("ms ", StringComparison.OrdinalIgnoreCase))
appName = appName.Substring("ms ".Length).Trim();
// Special case: "terminal" or "windows terminal" or "cmd" or "command prompt"
if (appName == "terminal" || appName == "windows terminal" || appName == "cmd" || appName == "command prompt")
appName = "terminal";
if (AppMappings.TryGetValue(appName, out var exe))
{
var action = new LaunchAppAction(exe);
AppendLog($"[DEBUG] InterpretAsync matched: {action.GetType().Name} (mapped app: {appName} -> {exe})\n");
return System.Threading.Tasks.Task.FromResult<ActionBase?>(action);
}
var embeddedAppName = AppMappings.Keys
.OrderByDescending(k => k.Length)
.FirstOrDefault(k => Regex.IsMatch(appName, $"\\b{Regex.Escape(k)}\\b", RegexOptions.IgnoreCase));
if (!string.IsNullOrWhiteSpace(embeddedAppName) && AppMappings.TryGetValue(embeddedAppName, out exe))
{
var action = new LaunchAppAction(exe);
AppendLog($"[DEBUG] InterpretAsync matched: {action.GetType().Name} (embedded mapped app: {embeddedAppName} -> {exe})\n");
return System.Threading.Tasks.Task.FromResult<ActionBase?>(action);
}
// Fallback: show Alt+Tab switcher and hold Alt
var fallbackAction = new LaunchAppAction("focus-fallback");
AppendLog($"[DEBUG] InterpretAsync fallback: {fallbackAction.GetType().Name} (focus-fallback for: {appName})\n");
return System.Threading.Tasks.Task.FromResult<ActionBase?>(fallbackAction);
}
// "type ..." maps to SendKeysAction
if (text.StartsWith("type "))
{
var keysText = text.Substring(5).Trim();
var action = new SendKeysAction(keysText);
AppendLog($"[DEBUG] InterpretAsync matched: {action.GetType().Name} (type keys)\n");
return System.Threading.Tasks.Task.FromResult<ActionBase?>(action);
}
// Emoji commands
// "emoji set <name> <emoji>" -> set mapping
if (text.StartsWith("emoji set "))
{
// Examples: "emoji set happy 😀" or "emoji set happy :D"
var rest = text.Substring("emoji set ".Length).Trim();
if (!string.IsNullOrEmpty(rest))
{
var parts = rest.Split(new[] { ' ' }, 2, StringSplitOptions.RemoveEmptyEntries);
if (parts.Length == 2)
{
var name = parts[0].Trim();