Repository navigation
Expand file tree
/
Copy pathKeyPlusKeyboard.cs
More file actions
2682 lines (2377 loc) · 120 KB
/
Copy pathKeyPlusKeyboard.cs
File metadata and controls
2682 lines (2377 loc) · 120 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 Android.App;
using Android.Content;
using Android.InputMethodServices;
using Android.Widget;
using Android.Runtime;
using Android.Views;
using Android.Views.InputMethods;
using Keycode = Android.Views.Keycode;
[assembly: UsesPermission(Berpiztu.KeyPlus.ScreenshotWatcher.Permission)]
namespace Berpiztu.KeyPlus;
/// <summary>
/// Berpiztu AI Keyboard: the <see cref="KeyPanel"/> as a keyboard of its
/// own, chosen in Android's keyboard list, on any Android. A headset
/// (Android XR) keeps the popup's window in front of the user's head, but
/// lets the user place a keyboard. The panel types straight into the editor; ABC is the whole
/// keyboard and Keys the strip's. Android sets where it stands and its width,
/// so ⤓ does not dock it; A− and A+ size the labels, ▭ makes it two rows,
/// – folds it into the ⌨ icon, and ⚙, in ✕'s place, shows its settings in
/// the keys' place, as Gboard does: on a phone Mover and Redimensionar (a
/// frame over the keyboard, <see cref="KeyboardFrame"/>), Modo normal, docked
/// at the bottom as wide as the screen, or Modo ventana, a window of its own
/// over the app, and the keyboard picker. Place and size are kept per screen
/// and mode, as the popup keeps them. It is a product of its own
/// (-p:KeyPlusProduct=Keyboard); the popup is the other.
/// </summary>
[Service(Name = "ai.berpiztu.keyboard.KeyPlusKeyboard", Label = "@string/keyboard_label",
Permission = "android.permission.BIND_INPUT_METHOD", Exported = true)]
[IntentFilter(["android.view.InputMethod"])]
[MetaData("android.view.im", Resource = "@xml/keyplus_keyboard")]
public sealed class KeyPlusKeyboard : InputMethodService
{
private KeyPanel? panel;
private PanelPlacement? placed;
/// <summary>The keys' size and the keyboard's height when a grip's drag started.</summary>
private (float Scale, int Height) resizeStart;
/// <summary>
/// Off a headset, what the keyboard's window holds: the keyboard
/// (<see cref="box"/>), at the bottom, or, in Modo ventana, anywhere in a
/// room as tall as the screen, the app's touches passing through it
/// (<see cref="OnComputeInsets"/>).
/// </summary>
private FrameLayout? container;
/// <summary>The keys, and over them, while Mover or Redimensionar is on, the <see cref="frame"/>.</summary>
private FrameLayout? box;
/// <summary>Docked, the keyboard's ground, as wide as the screen, behind the keys and under them: beside keys made narrower, as far as Mover raised them, and the navigation bar's room.</summary>
private View? ground;
private KeyboardFrame? frame;
/// <summary>Where the keyboard stood and how large it was when a drag on the frame or the title bar started.</summary>
private (int X, int Y, int Width, int Lift, float Scale, int Height) adjustStart;
/// <summary>The keyboard's place and size as Mover or Redimensionar found it, for Cancelar.</summary>
private (int X, int Y, int Width, float Scale, int Lift, int DockedX, int DockedWidth) frameStart;
/// <summary>The texts copied lately, which 📋 lists.</summary>
private ClipboardHistory? clipboard;
private ClipboardManager? clipboardManager;
/// <summary>Brings each new screenshot into the copied list, once the user lets the keyboard read the photos.</summary>
private ScreenshotWatcher? screenshots;
public override void OnCreate()
{
base.OnCreate();
// Sounds a dictation silenced and a keyboard that ended before giving them back left so.
VoicePreferences.GiveSoundsBack(this);
KeyPlusPreferences.SplitLayoutsOnce(this);
clipboard = new ClipboardHistory(this);
clipboardManager = (ClipboardManager?)GetSystemService(ClipboardService);
if (clipboardManager is not null)
{
clipboardManager.PrimaryClipChanged += OnCopied;
}
screenshots = new ScreenshotWatcher(this, clipboard);
screenshots.Start();
// The PC designs each screen kept before the list of keyboards, made keyboards of it once.
Keyboards.MoveDesignsOnce(this);
// FUTO Swipe and its word list, loaded once, away from the main thread, with the personal dictionary.
personal = new PersonalWords(Path.Combine(FilesDir!.AbsolutePath, PersonalWords.FileName));
personal.Reload();
swipeTyping = new SwipeTyping(this, language => personal.Words(language.Code));
spelling = new SpellingEngine(personal, code => LanguageChoices.Applied(this, code),
() => LanguageChoices.SpellingIn(this, StandardKeys.Spanish.Code).Wikipedia,
() => Assets!.Open(CommonErrors.OwnList), message => Log.Write(message));
spelling.FixesFound += (_, _) => panel?.OfferWords();
context = new(() => ContextModelOf(contextLanguage),
() => ContextModelOf(contextLanguage) is { } name
? ContextCorrector.Load(System.IO.Path.Combine(KeyPlusPreferences.CorrectorsFolder(this), name))
: null,
old => old.Dispose());
MenuWatchService.MenuOpened += AvoidMenu;
MenuWatchService.MenuClosed += MenuGone;
}
/// <summary>Words swiped over the letters, on a phone.</summary>
private SwipeTyping? swipeTyping;
/// <summary>The personal dictionary and the words chosen for swipes (<see cref="PersonalWords"/>), shared with the app's settings through their file.</summary>
private PersonalWords personal = null!;
/// <summary>How far back the field is read for the word being typed.</summary>
private const int WordReach = 48;
/// <summary>How far back the field is read for the sentence being typed (Spelling's sentence closed with ? or !).</summary>
private const int SentenceReach = 240;
/// <summary>What the keyboard knows of words as they are typed (<see cref="SpellingEngine"/>), shared with Windows: the words offered, whether a word is one, what it may have meant.</summary>
private SpellingEngine spelling = null!;
/// <summary>The context model of the language typed in (its Spelling's), loaded as the keyboard opens and again once the language or its model changes; only one in memory.</summary>
private Loaded<ContextCorrector> context = null!;
/// <summary>The language whose context model is loaded: the one typed in, as it was last prepared.</summary>
private string? contextLanguage;
/// <summary>A language's context model as the keyboard applies it: none with Spelling off.</summary>
/// <summary>What the context model last gave, with its percentages, for the Percentage for bold.</summary>
private IReadOnlyList<(string Word, double Probability)> lastScored = [];
private string? ContextModelOf(string? language) => language is null ? null : LanguageChoices.Applied(this, language).Context;
/// <summary>Swipes read as words; whether a language is swiped in is its own (its Glide typing, <see cref="LanguageChoices.Glides"/>).</summary>
private Func<KeyPanel.SwipePath, Task<IReadOnlyList<string>>>? SwipeOn() => swipeTyping is { } swiping ? swiping.Words : null;
/// <summary>
/// Whether the keyboard shows for the field: as Android decides (not
/// while a hardware keyboard is in), and never while the app's settings
/// have it off, for another keyboard in use; still the keyboard in use,
/// what a hardware keyboard types goes through it.
/// </summary>
public override bool OnEvaluateInputViewShown()
{
var kept = KeyPlusPreferences.Global(this);
return base.OnEvaluateInputViewShown()
&& (kept.GetBoolean(KeyPlusPreferences.ShowKeyboardKey, true) || kept.GetBoolean(KeyPlusPreferences.KeyboardIconKey, true));
}
/// <summary>
/// Its field let it go (Enter, the focus elsewhere): hidden, made its ⌨
/// icon, or kept on screen, as the app's settings say (Al perder el foco);
/// hidden all the same when the user asks, with ∨ or Back.
/// </summary>
public override void HideWindow()
{
var asked = hideAsked;
hideAsked = false;
var choice = KeyPlusPreferences.Global(this).GetString(KeyPlusPreferences.FocusLostKey, KeyPlusPreferences.FocusLostHide);
if (!asked && choice != KeyPlusPreferences.FocusLostHide)
{
Log.Detail($"Its field let it go: kept on screen ({choice})");
if (choice == KeyPlusPreferences.FocusLostIcon)
{
panel?.ShowAsIcon(true);
iconAsFieldLeft = true;
}
return;
}
base.HideWindow();
}
/// <summary>The keyboard became its icon as its field let it go: the next field opens it whole again.</summary>
private bool iconAsFieldLeft;
/// <summary>The user asked the keyboard to hide (∨, Back), which it does even while it stays on screen as its field lets it go.</summary>
private bool hideAsked;
public override bool OnKeyDown(Keycode keyCode, KeyEvent? e)
{
if (keyCode == Keycode.Back && IsInputViewShown)
{
hideAsked = true;
}
return base.OnKeyDown(keyCode, e);
}
/// <summary>The keyboard opening: the screenshots watched, if the user has let it read the photos since.</summary>
/// <summary>
/// Everything a language has turned on loaded at once, the owner's, as
/// the keyboard opens and as the language changes, not at its first use:
/// its Spelling's dictionary, misspellings and accent model, its word
/// list, and, with Glide typing on in it, FUTO Swipe's engine and its trie.
/// </summary>
private void PrepareLanguage(StandardLanguage language)
{
spelling.Prepare(language);
contextLanguage = language.Code;
_ = context.Async();
if (LanguageChoices.GlideOn(this))
{
swipeTyping?.Prepare(language);
}
}
/// <summary>The caret moved (a key typed, a tap in the text): Shift on where a sentence begins; an account's field's text kept, to be learnt as it is left.</summary>
public override void OnUpdateSelection(int oldSelStart, int oldSelEnd, int newSelStart, int newSelEnd, int candidatesStart, int candidatesEnd)
{
base.OnUpdateSelection(oldSelStart, oldSelEnd, newSelStart, newSelEnd, candidatesStart, candidatesEnd);
selection = (Math.Min(newSelStart, newSelEnd), Math.Max(newSelStart, newSelEnd));
SentenceShift();
if (accountField && CurrentInputConnection is { } field)
{
accountText = (field.GetTextBeforeCursor(AddressReach, 0)?.ToString() ?? "") + (field.GetTextAfterCursor(AddressReach, 0)?.ToString() ?? "");
}
}
/// <summary>
/// The kind of field typed in, as Android's field tells it: Estándar suits
/// it (<see cref="StandardField"/>); an e-mail address's, or one named or
/// hinted as a user's or an account's, offers the addresses the
/// dictionary has and keeps the one typed as it is left; a password's,
/// a number's or an address's is neither corrected nor offered words.
/// </summary>
private void TakeField(Android.Views.InputMethods.EditorInfo? info)
{
var type = info?.InputType ?? Android.Text.InputTypes.ClassText;
var kind = type & Android.Text.InputTypes.MaskClass;
var variation = type & Android.Text.InputTypes.MaskVariation;
fieldKind = kind switch
{
Android.Text.InputTypes.ClassNumber or Android.Text.InputTypes.ClassPhone or Android.Text.InputTypes.ClassDatetime => StandardField.Number,
Android.Text.InputTypes.ClassText when variation == Android.Text.InputTypes.TextVariationUri => StandardField.Web,
Android.Text.InputTypes.ClassText when variation is Android.Text.InputTypes.TextVariationEmailAddress or Android.Text.InputTypes.TextVariationWebEmailAddress => StandardField.Email,
_ => StandardField.Text,
};
secretField = (kind == Android.Text.InputTypes.ClassText && variation is Android.Text.InputTypes.TextVariationPassword
or Android.Text.InputTypes.TextVariationWebPassword or Android.Text.InputTypes.TextVariationVisiblePassword)
|| (kind == Android.Text.InputTypes.ClassNumber && variation == Android.Text.InputTypes.NumberVariationPassword);
var named = $"{info?.HintText} {info?.FieldName}";
accountField = !secretField && (fieldKind == StandardField.Email
|| (fieldKind == StandardField.Text && System.Text.RegularExpressions.Regex.IsMatch(named, AccountWords, System.Text.RegularExpressions.RegexOptions.IgnoreCase)));
accountText = "";
// Where Autocorrect may write by itself, as Gboard's base, AOSP's LatinIME (InputAttributes, at the revision the
// word lists are taken from), decides it (the owner, 2026-11-01: "as Gboard"): text with suggestions shown (no
// password, e-mail, web address, filter, no-suggestions or auto-complete field), the app asking for corrections
// (its auto-correct flag) or the field of many lines, a web page's field only with that flag.
var autoCorrectFlag = (type & Android.Text.InputTypes.TextFlagAutoCorrect) != 0;
documentField = WordsField && kind == Android.Text.InputTypes.ClassText && !secretField
&& variation is not (Android.Text.InputTypes.TextVariationEmailAddress or Android.Text.InputTypes.TextVariationWebEmailAddress
or Android.Text.InputTypes.TextVariationUri or Android.Text.InputTypes.TextVariationFilter)
&& (type & (Android.Text.InputTypes.TextFlagNoSuggestions | Android.Text.InputTypes.TextFlagAutoComplete)) == 0
&& !(variation == Android.Text.InputTypes.TextVariationWebEditText && !autoCorrectFlag)
&& (autoCorrectFlag || (type & Android.Text.InputTypes.TextFlagMultiLine) != 0);
panel?.FieldIs(fieldKind);
if (panel is not null)
{
panel.InDocument = documentField;
}
}
/// <summary>What names a user's or an account's field, in its hint or its name, in English or Spanish.</summary>
private const string AccountWords = "user|usuario|login|e-?mail|correo|account|cuenta";
/// <summary>How much of an account's field is read either side of the caret: an address at most.</summary>
private const int AddressReach = 320;
private StandardField fieldKind;
private bool secretField;
/// <summary>Whether the field is surely a document's (<see cref="TakeField"/>): only there does Autocorrect write by itself.</summary>
private bool documentField;
private bool accountField;
private string accountText = "";
/// <summary>Whether the field typed in is corrected and offered the words being typed: ordinary text alone, never a password, a number or an address.</summary>
private bool WordsField => fieldKind == StandardField.Text && !secretField && !accountField;
/// <summary>An account's field left: the address typed in it kept in the dictionary (Keep the e-mail addresses I type), once.</summary>
private void LearnAddress()
{
var typed = accountText.Trim();
accountText = "";
if (!accountField || !KeyPlusPreferences.Global(this).GetBoolean(KeyPlusPreferences.LearnEmailsKey, true)
|| !System.Text.RegularExpressions.Regex.IsMatch(typed, @"^[^@\s]+@[^@\s]+\.[^@\s]+$")
|| Addresses("").Contains(typed, StringComparer.OrdinalIgnoreCase))
{
return;
}
personal.Add(PersonalWords.Shared, typed);
Log.Write("Dictionary: an e-mail address typed in an account's field kept");
}
/// <summary>The e-mail addresses the dictionary has, every language's, those starting as the one typed.</summary>
private IReadOnlyList<string> Addresses(string typed) => personal.AddressesStarting(typed);
/// <summary>The field's selection as Android last told it, its start and end.</summary>
private (int Start, int End) selection;
/// <summary>
/// Shift tapped twice with text selected, the owner's: the selection
/// turned to the next case, all in capitals, then in small letters, then
/// its first letter a capital, and round again, from the one it is in
/// now (in another, capitals first); it stays selected, to turn again.
/// False where nothing is selected.
/// </summary>
private bool TurnSelectionCase()
{
if (CurrentInputConnection is not { } field || selection.End <= selection.Start
|| field.GetSelectedTextFormatted(0)?.ToString() is not { Length: > 0 } selected)
{
return false;
}
var turned = StandardKeys.NextCase(selected, new System.Globalization.CultureInfo(KeyPlusPreferences.Language(this).Locale));
field.BeginBatchEdit();
field.CommitText(turned, 1);
field.SetSelection(selection.Start, selection.Start + turned.Length);
field.EndBatchEdit();
return true;
}
/// <summary>
/// Spelling's Capital at the start of a sentence, on: Shift on by itself
/// where the field says a sentence begins, as Gboard's; Android's own
/// reading of it (after . ? or ! and a space, a new line, the field's
/// start), only in a field that asks for capitals there (CAP_SENTENCES:
/// never an address, a password or a number) and is a document's
/// (Autocorrect's own rule), and only while Spelling is on: off, nothing
/// is corrected, a sentence's capital neither.
/// </summary>
private void SentenceShift()
{
if (panel is null || CurrentInputEditorInfo is not { } info)
{
return;
}
var on = KeyPlusPreferences.Global(this).GetBoolean(KeyPlusPreferences.CapitalizeSentencesKey, false) && LanguageChoices.SpellingOn(this);
panel.SentenceStart(on && documentField && CurrentInputConnection?.GetCursorCapsMode((Android.Text.CapitalizationMode)(int)info.InputType) is { } mode && mode != 0);
}
public override void OnStartInputView(Android.Views.InputMethods.EditorInfo? info, bool restarting)
{
base.OnStartInputView(info, restarting);
ForgetSpoken("the field started again");
// Once a day at most: the keyboard's process lives for days.
AndroidUpdates.CheckInBackground(this);
// The app's Dictionary may have changed the words: swiping reads them again.
if (personal.Reload())
{
swipeTyping?.Forget();
}
InAppColors(info?.PackageName);
panel?.FitLabels();
if (panel is not null && !OnHeadset)
{
panel.ReadSettings();
panel.Swiping = SwipeOn();
panel.ForgetTyping();
panel.EndEmojiSearch();
spelling.Forget();
PrepareLanguage(KeyPlusPreferences.Language(this));
TakeEdited();
panel.GridTiles = GridTiles();
panel.PreviewAgain();
TakeField(info);
SentenceShift();
// Not shown, for another keyboard in use: its ⌨ icon in its place, which a tap opens. Made its
// icon as the last field let it go, whole again for this one.
if (!KeyPlusPreferences.Global(this).GetBoolean(KeyPlusPreferences.ShowKeyboardKey, true))
{
panel.ShowAsIcon(true);
}
else if (iconAsFieldLeft)
{
panel.ShowAsIcon(false);
}
iconAsFieldLeft = false;
// The caret's place on the screen, now and as it moves, for a keyboard in a window to keep clear of it.
var followed = CurrentInputConnection?.RequestCursorUpdates((int)(CursorUpdate.Immediate | CursorUpdate.Monitor)) == true;
caretSkipLogged = null;
Log.Detail($"Field of {info?.PackageName}: its caret {(followed ? "followed" : "not told by the app")}");
}
screenshots?.Start();
}
public override void OnDestroy()
{
if (clipboardManager is not null)
{
clipboardManager.PrimaryClipChanged -= OnCopied;
}
screenshots?.Stop();
dictation?.Dispose();
MenuWatchService.MenuOpened -= AvoidMenu;
MenuWatchService.MenuClosed -= MenuGone;
base.OnDestroy();
}
/// <summary>🎤's dictation going on: by Android's own recognizer (Local) or ia-voice at an address, as Escribir por voz says.</summary>
private IDictation? dictation;
private bool transcribing;
/// <summary>The space a dictation's words need before them: none after a space or nothing.</summary>
private string? spokenLead;
/// <summary>The field's text was sent while a dictation was stopping: its last words are not written again.</summary>
private bool sentWhileStopping;
/// <summary>The chosen service being asked whether it answers, before listening: 🎤 again waits for it.</summary>
private bool asking;
/// <summary>
/// 🎤 tapped: a dictation started, its words written in the field as they
/// are heard (Android's composing text, underlined as Gboard's), or the
/// one going on stopped and its words written for good. Without the
/// microphone's permission, the app asks for it. The local network's or
/// the remote service not answering (no network, the server down),
/// Android's own recognizer listens instead, and says so.
/// </summary>
private async void Dictate()
{
if (transcribing || asking)
{
return;
}
if (dictation is { Recording: true })
{
EndDictation();
return;
}
if (CheckSelfPermission(Android.Manifest.Permission.RecordAudio) != Android.Content.PM.Permission.Granted)
{
Toast.MakeText(this, Resource.String.voice_permission_asked, ToastLength.Long)!.Show();
StartActivity(new Intent(this, typeof(MainActivity)).AddFlags(ActivityFlags.NewTask).PutExtra(MainActivity.AskMicrophoneExtra, true));
return;
}
var locale = panel?.DictationLocale ?? StandardKeys.Spanish.Locale;
var local = VoicePreferences.Local(this);
if (!local)
{
asking = true;
var answers = await VoiceTyping.Answers(VoicePreferences.Options(this, locale).Service);
asking = false;
if (!answers)
{
Log.Write($"Voice typing: {VoicePreferences.Choice(this)} did not answer, so Android's recognizer listens");
Notice(Resource.String.voice_fallback_local);
local = true;
}
}
dictation?.Dispose();
IDictation made;
VoiceOptions options;
if (local)
{
var speech = new AndroidSpeech(this, Log.Write);
if (!speech.Available)
{
Notice(Resource.String.voice_unavailable);
return;
}
made = speech;
options = new VoiceOptions(VoicePreferences.AutoStop(this), VoicePreferences.Silence(this), 1, "", "", "", locale);
}
else
{
made = new VoiceTyping(new AndroidMicrophone(this), Log.Write);
options = VoicePreferences.Options(this, locale);
}
made.Level += level =>
{
if (dictation == made && made.Recording)
{
panel?.ShowListening(true, level, made.Speaking);
}
};
made.Partial += text =>
{
if (dictation != made || !made.Recording)
{
return;
}
var said = VoiceCommands.Apply(text, locale, open: true, spokenCase);
spokenCaseNow = said.Case;
#if DEBUG
// A Debug build alone: what was heard with a command in it, to learn how the recognizer writes them.
// The last utterance alone, whole: a command whose keyword the recognizer lost has no "comando" to tell it by.
var last = text[(text.LastIndexOf(VoiceCommands.UtteranceBreak, StringComparison.Ordinal) + 1)..].Trim();
if (last != heardLogged)
{
heardLogged = last;
Log.Write($"Voice typing (Debug build only): heard \"{last}\"");
}
#endif
// Nothing to write and nothing of the dictation's written: the field is left alone, for writing nothing
// over what a command selected would delete it.
if (said.Text.Length > 0 || spokenShown)
{
if (selectedByCommand && !spokenShown)
{
// Words after a command's selection go after it, never in its place: a command not understood,
// written as words, deleted all that was selected.
selectedByCommand = false;
if (CurrentInputConnection?.GetExtractedText(new Android.Views.InputMethods.ExtractedTextRequest(), 0) is { } held)
{
var end = held.StartOffset + Math.Max(held.SelectionStart, held.SelectionEnd);
CurrentInputConnection.SetSelection(end, end);
spokenLead = null;
}
}
CurrentInputConnection?.SetComposingText(WithLead(said.Text), 1);
spokenShown = said.Text.Length > 0;
}
SayUnderstood(said);
CommandsSaid(said, locale);
};
made.Silence += EndDictation;
spokenLead = null;
spokenLocale = locale;
ForgetCommands();
Lead();
try
{
made.Start(options);
}
catch (Exception none) when (none is InvalidOperationException or Java.Lang.Exception)
{
Log.Write($"The microphone could not listen: {none.Message}");
Notice(Resource.String.voice_no_microphone);
made.Dispose();
return;
}
dictation = made;
selectedByCommand = false;
spokenCase = spokenCaseNow = VoiceCase.AsHeard;
Log.Write($"Voice typing: listening by {(local ? "Android's recognizer" : VoicePreferences.Choice(this))}, {(options.AutoStop ? $"stopping after {options.SilenceSeconds} s of silence" : "until the microphone is tapped")}");
panel?.ShowListening(true, 0);
}
/// <summary>The space the words heard need before them, read from the field the first time it is asked after a dictation starts or starts afresh.</summary>
private string Lead()
{
if (spokenLead is null)
{
var before = CurrentInputConnection?.GetTextBeforeCursor(1, 0)?.ToString();
spokenLead = string.IsNullOrEmpty(before) || char.IsWhiteSpace(before[^1]) ? "" : " ";
}
return spokenLead;
}
/// <summary>A dictation's text as it is written: the space it needs before it, unless it starts with something written against what is there (a mark, a new line).</summary>
private string WithLead(string text) => text.Length == 0 || VoiceCommands.StartsAttached(text) ? text : Lead() + text;
/// <summary>The language the dictation going on is heard in, by its locale: its commands' marks and Help's list.</summary>
private string spokenLocale = StandardKeys.Spanish.Locale;
/// <summary>How long a dictation's commands for the keyboard (send, stop, help) must stand as heard before they are done: the recognizer changes its last words while they are being said.</summary>
private const int CommandStandsMs = 700;
/// <summary>How much of the field before the caret is read to find the word or the sentence a command deletes.</summary>
private const int DeleteReach = 1000;
private readonly Android.OS.Handler commandsHandler = new(Android.OS.Looper.MainLooper!);
/// <summary>The commands for the keyboard the dictation going on holds, as last heard, how many of them were done already, and how many were waited on.</summary>
private IReadOnlyList<VoiceAction> commandsHeard = [];
private int commandsDone;
private int commandsWaited;
/// <summary>Whether the dictation going on has words of its own written in the field (its composing text).</summary>
private bool spokenShown;
/// <summary>How the dictation going on writes its words from its start, or from where it last started afresh (capitals or small letters asked for before then), and how it is writing them now.</summary>
private VoiceCase spokenCase;
private VoiceCase spokenCaseNow;
/// <summary>A command of the dictation going on selected text that is still selected for all the keyboard knows: its next words are written after it.</summary>
private bool selectedByCommand;
#if DEBUG
/// <summary>What was last written in the log as heard, in a Debug build.</summary>
private string heardLogged = "";
#endif
/// <summary>A dictation starting, or starting afresh: no command of its own heard or done yet, and no words of its own written.</summary>
private void ForgetCommands()
{
spokenShown = false;
understoodSaid = "";
understoodCount = 0;
commandsHandler.RemoveCallbacksAndMessages(null);
commandsHeard = [];
commandsDone = 0;
commandsWaited = 0;
}
/// <summary>
/// The commands for the keyboard in the words heard so far: a new one is
/// done once, when it has stood as heard for <see cref="CommandStandsMs"/>;
/// the words are read again whole each time, so those done before are
/// still there and are not done again.
/// </summary>
private void CommandsSaid(Spoken said, string locale)
{
commandsHeard = said.Actions;
if (said.Actions.Count == commandsWaited)
{
return;
}
commandsWaited = said.Actions.Count;
commandsHandler.RemoveCallbacksAndMessages(null);
if (commandsWaited > commandsDone)
{
commandsHandler.PostDelayed(() => DoCommands(locale), CommandStandsMs);
}
}
private void DoCommands(string locale)
{
if (dictation is not { Recording: true } || transcribing)
{
return;
}
var asked = commandsHeard.Skip(commandsDone).ToArray();
commandsDone = commandsHeard.Count;
foreach (var action in asked)
{
Log.Write($"Voice typing: command {action}");
switch (action)
{
case VoiceAction.Send:
// Enter starts the dictation afresh, its commands with it: those said after it are heard anew.
PerformEnter();
return;
case VoiceAction.Stop:
EndDictation();
return;
case VoiceAction.Help:
panel?.ShowVoiceHelp(VoiceCommands.HelpTitle(locale), VoiceCommands.Help(locale));
break;
case VoiceAction.DeleteWord:
DeleteBefore(sentence: false);
break;
case VoiceAction.DeleteSentence:
DeleteBefore(sentence: true);
break;
case VoiceAction.SelectAll:
Select(paragraph: false);
break;
case VoiceAction.SelectParagraph:
Select(paragraph: true);
break;
case VoiceAction.DeleteSelection:
if (CurrentInputConnection is { } field && field.GetSelectedText(0) is { } chosen && chosen.Length > 0)
{
field.CommitText("", 1);
}
break;
case VoiceAction.Copy:
CurrentInputConnection?.PerformContextMenuAction(Android.Resource.Id.Copy);
break;
case VoiceAction.Cut:
AfreshForCommand();
CurrentInputConnection?.PerformContextMenuAction(Android.Resource.Id.Cut);
break;
case VoiceAction.Paste:
AfreshForCommand();
CurrentInputConnection?.PerformContextMenuAction(Android.Resource.Id.Paste);
break;
case VoiceAction.GoEnd:
GoTo(end: true);
break;
case VoiceAction.GoStart:
GoTo(end: false);
break;
case VoiceAction.Spelling:
CorrectSelected();
break;
case VoiceAction.Grammar:
MarkGrammar();
break;
case VoiceAction.SelectionCase:
// Text selected: its case turned, as Shift tapped twice does, and the words after it written as before the command.
if ((CurrentInputConnection?.GetSelectedText(0)?.Length ?? 0) > 0)
{
var before = spokenCase;
AfreshForCommand();
spokenCase = spokenCaseNow = before;
TurnSelectionCase();
}
break;
case VoiceAction.Undo:
AfreshForCommand();
selectedByCommand = false;
if (!TakeCorrectionBack())
{
PressKey(Keycode.Z, MetaKeyStates.CtrlOn | MetaKeyStates.CtrlLeftOn);
}
break;
}
}
}
/// <summary>
/// A command that selects or changes the field's text by itself (select,
/// cut, paste): the dictation's words so far are written for good first
/// and it starts afresh, keeping what was said after the command, so its
/// next words neither move the caret off a selection nor write over what
/// the command did, nor the command's own again.
/// </summary>
private void AfreshForCommand()
{
CurrentInputConnection?.FinishComposingText();
dictation?.Forget(keepUnread: true);
ForgetCommands();
spokenCase = spokenCaseNow;
spokenLead = null;
}
/// <summary>A sentence as what corrects the language writes it, away from the keyboard's thread: Android's own spell checker where it is the one chosen (its misspellings as its first suggestion), else its context model where it is on (one loaded for another language is not used), else the accent model; none where none of them is there.</summary>
private async Task<string?> CorrectedSentence(StandardLanguage language, string sentence) =>
LanguageChoices.Applied(this, language.Code).System ? await CorrectedBySystem(language, sentence)
: ContextModelOf(language.Code) is { } name
? await context.Async() is { } corrector && corrector.Name == name ? await Task.Run(() => corrector.Correct(sentence)) : null
: await spelling.Accents.Async() is { } model ? await Task.Run(() => model.Restore(sentence)) : null;
/// <summary>A message of the dictation's, said in the keyboard's toolbar, where the words offered show (the owner, 2026-11-14); floating on the screen only where the toolbar is not there.</summary>
private void Notice(int text, bool lasting = false) => Notice(GetString(text), lasting);
private void Notice(string text, bool lasting = false)
{
if (panel?.Say(text, lasting) != true)
{
Toast.MakeText(this, text, lasting ? ToastLength.Long : ToastLength.Short)!.Show();
}
}
/// <summary>The last command said in the toolbar as understood, and how many the dictation going on had then: a new one, or the last heard otherwise, is said.</summary>
private string understoodSaid = "";
private int understoodCount;
/// <summary>What was heard after the keyword said in the toolbar as it is understood (the owner, 2026-11-14): the command it was taken for, or the words no command is near to, so it is seen why one is not done.</summary>
private void SayUnderstood(Spoken said)
{
if (said.Understood.Count == 0 || (said.Understood.Count == understoodCount && said.Understood[^1] == understoodSaid))
{
return;
}
understoodCount = said.Understood.Count;
understoodSaid = said.Understood[^1];
Notice(understoodSaid);
}
/// <summary>A sentence typed as Android's own spell checker corrects it, its misspellings as its first suggestion; none where it does not answer. With the detailed log on, how much it was asked about and how much it marked, never the text.</summary>
private async Task<string?> CorrectedBySystem(StandardLanguage language, string sentence)
{
if (await (systemSpelling ??= new(this, Log.Write)).Check(sentence, language.Locale) is not { } marked)
{
return null;
}
var (text, changed) = SystemSpelling.Corrected(sentence, marked);
Log.Detail($"Spelling: Android's spell checker asked about {sentence.Length} characters typed in {language.Code}: {marked.Count(place => place.Misspelled)} misspellings marked, {changed} with a word to write");
return text;
}
/// <summary>The Spelling command is reading a text: a second one waits for it.</summary>
private bool correcting;
/// <summary>What the Spelling command last wrote, where, and what was there before, while it has not been taken back: Undo puts it back as it was.</summary>
private (int At, string Written, string Before)? lastCorrection;
/// <summary>
/// The Spelling command's last correction taken back by Undo: the text as
/// it was before it, written again in its place, while what it wrote is
/// still there. The field's own undo does not know how: on the owner's
/// headset it deleted the whole paragraph (2026-11-14). False where there
/// is none to take back, or the text is no longer what it wrote.
/// </summary>
private bool TakeCorrectionBack()
{
if (lastCorrection is not { } last)
{
return false;
}
lastCorrection = null;
if (CurrentInputConnection is not { } field || field.GetExtractedText(new Android.Views.InputMethods.ExtractedTextRequest(), 0) is not { Text: { } held } extracted)
{
return false;
}
var at = last.At - extracted.StartOffset;
var text = held.ToString() ?? "";
if (at < 0 || at + last.Written.Length > text.Length || text.Substring(at, last.Written.Length) != last.Written)
{
Log.Write("Voice typing: the text is no longer what Spelling wrote, so Undo is the field's own");
return false;
}
field.SetSelection(last.At, last.At + last.Written.Length);
field.CommitText(last.Before, 1);
Log.Write("Voice typing: Spelling's correction taken back, the text as it was before it");
return true;
}
/// <summary>Android's own spell checker, asked by the Spelling command where the language has it chosen, and by the Grammar command.</summary>
private SystemSpelling? systemSpelling;
/// <summary>The text a command reads: where the field's text starts, the part of it chosen, and that part as it was read.</summary>
private sealed record Chosen(int Offset, int Start, int End, string Text);
/// <summary>
/// The text a command reads (Spelling, Grammar): what is selected, or all
/// the text where nothing is, the dictation's words so far written for
/// good first; none where the field's text cannot be read or is empty.
/// </summary>
private Chosen? ChosenForCommand(string command)
{
if (CurrentInputConnection is not { } field)
{
return null;
}
AfreshForCommand();
if ((field.GetSelectedText(0)?.Length ?? 0) == 0)
{
Select(paragraph: false);
}
if (field.GetExtractedText(new Android.Views.InputMethods.ExtractedTextRequest(), 0) is not { Text: { } held } extracted)
{
Log.Write($"Voice typing: the field's text could not be read, so {command} did nothing");
return null;
}
var whole = held.ToString() ?? "";
var start = Math.Clamp(Math.Min(extracted.SelectionStart, extracted.SelectionEnd), 0, whole.Length);
var end = Math.Clamp(Math.Max(extracted.SelectionStart, extracted.SelectionEnd), 0, whole.Length);
var text = whole[start..end];
return text.Trim().Length == 0 ? null : new(extracted.StartOffset, start, end, text);
}
/// <summary>
/// A command's text written in the place of what it read, found by where
/// it was, only while that part of the field is still what was read: what
/// was said or typed after it meanwhile stays. With what was there
/// before kept, where Undo is to put it back (<see cref="TakeCorrectionBack"/>).
/// False where the text changed meanwhile, which is left as it is.
/// </summary>
private bool WriteOverChosen(Chosen read, Java.Lang.ICharSequence written, bool undone)
{
if (CurrentInputConnection is { } now && now.GetExtractedText(new Android.Views.InputMethods.ExtractedTextRequest(), 0) is { Text: { } after } found
&& found.StartOffset == read.Offset && after.Length() >= read.End && (after.ToString() ?? "")[read.Start..read.End] == read.Text)
{
now.FinishComposingText();
now.SetSelection(read.Offset + read.Start, read.Offset + read.End);
now.CommitText(written, 1);
lastCorrection = undone ? (read.Offset + read.Start, written.ToString() ?? "", read.Text) : null;
selectedByCommand = false;
return true;
}
Log.Write("Voice typing: the text changed while it was read, so it was left as it is");
return false;
}
/// <summary>
/// The Spelling command: what is selected, or all the text where nothing
/// is, corrected by what the language's Spelling has chosen in the
/// settings (the owner, 2026-11-14), whether or not Spelling is turned
/// off from the toolbar: Android's own spell checker where it is chosen
/// (its misspellings written as its first suggestion); else the
/// language's context model alone where it is chosen, loaded for this
/// where the keyboard has it not loaded; else its words as Correct words
/// writes a misspelled one, then its accents by the accent model. It
/// says in the keyboard's line that it is reading, a model taking many
/// seconds for a long text, and how it ended.
/// </summary>
private async void CorrectSelected()
{
if (correcting)
{
Notice(Resource.String.voice_spelling_working);
return;
}
if (ChosenForCommand("Spelling") is not { } read)
{
return;
}
var language = KeyPlusPreferences.Language(this);
var bySystem = LanguageChoices.SystemSpellingIn(this, language.Code);
var set = LanguageChoices.SpellingIn(this, language.Code).Alone();
Log.Write($"Voice typing: Spelling in {language.Code} as its language has it chosen: Android's spell checker {(bySystem ? "on" : "off")}, context model {set.Context ?? "off"}, Correct words {(set.Words ? "on" : "off")}, accents {(set.Accents ? "on" : "off")}");
if (!bySystem && set.Context is null && !set.Words && !set.Accents)
{
Notice(Resource.String.voice_spelling_nothing);
return;
}
correcting = true;
Notice(Resource.String.voice_spelling_working, lasting: true);
ContextCorrector? own = null;
try
{
string written;
int changed;
if (bySystem)
{
if (await (systemSpelling ??= new(this, Log.Write)).Check(read.Text, language.Locale) is not { } marked)
{
Notice(Resource.String.voice_spelling_no_system);
return;
}
(written, changed) = SystemSpelling.Corrected(read.Text, marked);
Log.Write($"Voice typing: Android's spell checker marked {marked.Count(place => place.Misspelled)} misspellings and {marked.Count(place => place.Grammar)} grammar errors in {read.Text.Length} characters; {changed} were corrected");
}
else
{
ContextCorrector? corrector = null;
if (set.Context is { } name)
{
// The keyboard's own where it is the one loaded; else, Spelling being off from the toolbar, loaded for this reading alone.
corrector = await context.Async() is { } loaded && loaded.Name == name
? loaded
: own = await Task.Run(() => ContextCorrector.Load(System.IO.Path.Combine(KeyPlusPreferences.CorrectorsFolder(this), name)));
if (corrector is null)
{
Log.Write($"Voice typing: the context model chosen for {language.Code} is not there, so nothing was corrected");
Notice(Resource.String.voice_spelling_no_model);
return;
}
}
else if (set.Words && spelling.DictionaryFor(language) is { } dictionary && await dictionary.Async() is null)
{
Log.Write($"Voice typing: {language.Code}'s dictionary is not downloaded, so its words are not corrected");
}
var accents = corrector is null && set.Accents ? await spelling.Accents.Async() : null;
var parts = VoiceCommands.SentencesOf(read.Text);
changed = 0;
for (var at = 0; at < parts.Length; at += 2)
{
var sentence = parts[at];
if (sentence.Trim().Length == 0)
{
continue;
}
string corrected;
if (corrector is not null)
{
corrected = await Task.Run(() => corrector.Correct(sentence));
}
else
{
var words = set.Words
? VoiceCommands.WordsCorrected(sentence, word => spelling.FixAsChosen(language, word) is { Misspelled: true, Words: [var first, ..] } ? first : null)
: sentence;
corrected = accents is null ? words : await Task.Run(() => accents.Restore(words));
}
changed += corrected == sentence ? 0 : 1;
parts[at] = corrected;
}
written = string.Concat(parts);