Repository navigation
Expand file tree
/
Copy pathVoiceTextBox.cs
More file actions
360 lines (318 loc) · 11.8 KB
/
Copy pathVoiceTextBox.cs
File metadata and controls
360 lines (318 loc) · 11.8 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
using Microsoft.UI.Dispatching;
using Microsoft.UI.Input;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Input;
using Quicki.Services;
using Windows.Security.Authorization.AppCapabilityAccess;
using Windows.UI.Core;
using VirtualKey = Windows.System.VirtualKey;
namespace Quicki;
/// <summary>
/// A TextBox that looks and types exactly like the stock one, except that pressing and holding the
/// spacebar for <see cref="HoldDelay"/> starts push-to-talk dictation on a local Whisper model.
/// Recognized phrases are inserted at the caret while the key is held, and releasing the spacebar
/// finalizes the last chunk. A quick tap still types an ordinary space.
/// </summary>
/// <remarks>
/// The spacebar is intercepted on key-down (so holding it doesn't type a run of spaces) and the space is
/// committed on key-up, or just before the next key is handled, so typing order is preserved.
/// </remarks>
public sealed class VoiceTextBox : TextBox
{
public static readonly DependencyProperty VoiceStatusProperty = DependencyProperty.Register(
nameof(VoiceStatus), typeof(string), typeof(VoiceTextBox), new PropertyMetadata(string.Empty));
public static readonly DependencyProperty AccessHintProperty = DependencyProperty.Register(
nameof(AccessHint), typeof(string), typeof(VoiceTextBox), new PropertyMetadata(string.Empty));
private readonly DispatcherQueueTimer _holdTimer;
private readonly DispatcherQueueTimer _statusClearTimer;
private IVoiceDictationService? _voice;
private bool _isLoaded;
private bool _spaceHeld;
private bool _spacePending;
private bool _voiceActive;
private bool _ending;
public VoiceTextBox()
{
// Derived controls look for their own default style; reuse the stock TextBox template.
DefaultStyleKey = typeof(TextBox);
_holdTimer = DispatcherQueue.CreateTimer();
_holdTimer.IsRepeating = false;
_holdTimer.Tick += OnHoldElapsed;
_statusClearTimer = DispatcherQueue.CreateTimer();
_statusClearTimer.IsRepeating = false;
_statusClearTimer.Interval = TimeSpan.FromSeconds(3);
_statusClearTimer.Tick += (_, _) =>
{
_statusClearTimer.Stop();
if (_isLoaded && !_voiceActive)
VoiceStatus = string.Empty;
};
PreviewKeyDown += OnPreviewKeyDown;
PreviewKeyUp += OnPreviewKeyUp;
LostFocus += OnLostFocus;
Unloaded += OnUnloaded;
Loaded += OnLoaded;
GotFocus += OnRefreshAccess; // e.g. back from the Windows privacy settings
}
/// <summary>
/// A subtle call to action while the microphone isn't usable yet ("Enable voice typing", or a pointer to
/// the privacy settings when blocked); empty once access is granted. Activate it with <see cref="RequestMicrophoneAccessAsync"/>.
/// </summary>
public string AccessHint
{
get => (string)GetValue(AccessHintProperty);
private set => SetValue(AccessHintProperty, value);
}
private static bool IsBlocked(AppCapabilityAccessStatus status) =>
status is AppCapabilityAccessStatus.DeniedByUser or AppCapabilityAccessStatus.DeniedBySystem;
private static bool NeedsPrompt(AppCapabilityAccessStatus status) =>
status == AppCapabilityAccessStatus.UserPromptRequired;
private async void OnLoaded(object sender, RoutedEventArgs e)
{
_isLoaded = true;
await RefreshAccessAsync();
}
private void OnUnloaded(object sender, RoutedEventArgs e)
{
_isLoaded = false;
_statusClearTimer.Stop();
OnLostFocus(sender, e);
}
private async void OnRefreshAccess(object sender, RoutedEventArgs e)
{
if (_isLoaded)
await RefreshAccessAsync();
}
/// <summary>Reads (never prompts for) microphone access and updates <see cref="AccessHint"/>.</summary>
private async Task<AppCapabilityAccessStatus> RefreshAccessAsync()
{
AppCapabilityAccessStatus status;
try
{
status = await CheckMicrophoneAccessAsync();
}
catch (Exception ex)
{
Trace.Error("Voice", "check microphone access", ex);
status = AppCapabilityAccessStatus.Allowed; // unknown: let a hold try, it reports its own failure
}
if (_isLoaded)
{
AccessHint = IsBlocked(status) ? "Microphone blocked · open settings"
: NeedsPrompt(status) ? "Enable voice typing"
: string.Empty;
}
return status;
}
/// <summary>
/// Asks Windows for microphone access (showing its consent prompt) or, if it was refused, opens the
/// privacy settings. Called from the hint, so the prompt never appears in the middle of a spacebar hold.
/// </summary>
public async Task RequestMicrophoneAccessAsync()
{
try
{
AppCapabilityAccessStatus status = await CheckMicrophoneAccessAsync();
if (IsBlocked(status))
await Windows.System.Launcher.LaunchUriAsync(new Uri("ms-settings:privacy-microphone"));
else
await AppCapability.Create("microphone").RequestAccessAsync();
}
catch (Exception ex)
{
Trace.Error("Voice", "request microphone access", ex);
}
finally
{
await RefreshAccessAsync();
if (_isLoaded)
Focus(FocusState.Programmatic);
}
}
private static Task<AppCapabilityAccessStatus> CheckMicrophoneAccessAsync() =>
Task.Run(static () => AppCapability.Create("microphone").CheckAccess());
/// <summary>How long the spacebar must be held before dictation starts.</summary>
public TimeSpan HoldDelay { get; set; } = TimeSpan.FromSeconds(1);
/// <summary>Short progress text while dictating ("Listening…"); empty when idle.</summary>
public string VoiceStatus
{
get => (string)GetValue(VoiceStatusProperty);
private set => SetValue(VoiceStatusProperty, value);
}
private IVoiceDictationService Voice => _voice ??= App.GetService<IVoiceDictationService>();
private static bool IsDown(VirtualKey key) =>
InputKeyboardSource.GetKeyStateForCurrentThread(key).HasFlag(CoreVirtualKeyStates.Down);
private void OnPreviewKeyDown(object sender, KeyRoutedEventArgs e)
{
bool plainSpace = e.Key == VirtualKey.Space && !IsDown(VirtualKey.Control) && !IsDown(VirtualKey.Menu);
if (plainSpace && !IsReadOnly)
{
e.Handled = true;
if (e.KeyStatus.WasKeyDown)
return; // auto-repeat while held
_spaceHeld = true;
_spacePending = true;
_holdTimer.Interval = HoldDelay;
_holdTimer.Start();
return;
}
// Any other key while a tapped space is still waiting: type the space first, keep the order.
CommitPendingSpace();
}
private void OnPreviewKeyUp(object sender, KeyRoutedEventArgs e)
{
if (e.Key != VirtualKey.Space)
return;
_spaceHeld = false;
if (_spacePending)
{
e.Handled = true;
CommitPendingSpace(); // a tap, not a hold
}
else if (_voiceActive)
{
e.Handled = true;
_ = EndVoiceAsync(); // release: flush the last chunk
}
}
private void OnLostFocus(object sender, RoutedEventArgs e)
{
_spaceHeld = false;
CommitPendingSpace();
if (_voiceActive)
_ = EndVoiceAsync();
}
private async void OnHoldElapsed(DispatcherQueueTimer sender, object args)
{
sender.Stop();
if (_isLoaded && _spacePending && _spaceHeld)
{
_spacePending = false;
// Never open the microphone here unless access is already granted: Windows' consent prompt
// would steal focus mid-hold. The hint beside the box handles first-time setup instead.
AppCapabilityAccessStatus access = await RefreshAccessAsync();
if (!_spaceHeld)
return;
if (IsBlocked(access) || NeedsPrompt(access))
{
VoiceStatus = "Enable the microphone first →";
_statusClearTimer.Start();
return;
}
_ = BeginVoiceAsync();
}
}
private void CommitPendingSpace()
{
_holdTimer.Stop();
if (!_spacePending)
return;
_spacePending = false;
InsertAtCaret(" ");
}
private async Task BeginVoiceAsync()
{
_statusClearTimer.Stop();
_voiceActive = true;
if (_isLoaded)
VoiceStatus = "Listening…";
Voice.PhraseRecognized += OnPhraseRecognized;
Voice.StatusChanged += OnStatusChanged;
bool started = false;
try
{
started = await Voice.StartAsync();
}
catch (Exception ex)
{
Trace.Error("Voice", "start failed", ex);
}
if (!started)
{
Detach();
_voiceActive = false;
if (_isLoaded)
{
if (string.IsNullOrEmpty(VoiceStatus) || VoiceStatus == "Listening…")
VoiceStatus = "Voice typing unavailable.";
_statusClearTimer.Start();
}
return;
}
// The key may have been released while the microphone was still starting.
if (!_spaceHeld)
await EndVoiceAsync();
}
private async Task EndVoiceAsync()
{
if (_ending)
return;
_ending = true;
try
{
if (_isLoaded)
VoiceStatus = "Finishing…";
// StopAsync raises the final phrase before it completes; that delivery is queued to the
// UI thread ahead of this continuation, so the text lands before the status clears.
await Voice.StopAsync();
}
catch (Exception ex)
{
Trace.Error("Voice", "stop failed", ex);
}
finally
{
Detach();
_voiceActive = false;
_ending = false;
if (_isLoaded)
VoiceStatus = string.Empty;
}
}
private void Detach()
{
Voice.PhraseRecognized -= OnPhraseRecognized;
Voice.StatusChanged -= OnStatusChanged;
}
private void OnPhraseRecognized(object? sender, string text) =>
DispatcherQueue.TryEnqueue(() =>
{
if (_isLoaded)
InsertPhrase(text);
});
private void OnStatusChanged(object? sender, string status) =>
DispatcherQueue.TryEnqueue(() =>
{
if (_isLoaded && _voiceActive && !_ending)
VoiceStatus = status;
});
/// <summary>Inserts a dictated phrase at the caret, adding a separating space after existing text.</summary>
private void InsertPhrase(string text)
{
string phrase = text.Trim();
if (phrase.Length == 0)
return;
int start = SelectionStart;
string current = Text;
if (start > 0 && start <= current.Length && !char.IsWhiteSpace(current[start - 1]))
phrase = " " + phrase;
InsertAtCaret(phrase);
}
/// <summary>Replaces the selection with <paramref name="insert"/> (honoring MaxLength) and parks the caret after it.</summary>
private void InsertAtCaret(string insert)
{
if (MaxLength > 0)
{
int room = MaxLength - (Text.Length - SelectionLength);
if (room <= 0)
return;
if (insert.Length > room)
insert = insert[..room];
}
int start = SelectionStart;
SelectedText = insert;
SelectionStart = start + insert.Length;
SelectionLength = 0;
}
}