-
Notifications
You must be signed in to change notification settings - Fork 118
Expand file tree
/
Copy pathGeneralKeyboardIME.kt
More file actions
2058 lines (1841 loc) · 80.5 KB
/
Copy pathGeneralKeyboardIME.kt
File metadata and controls
2058 lines (1841 loc) · 80.5 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
// SPDX-License-Identifier: GPL-3.0-or-later
package be.scri.services
import DataContract
import android.R.color.white
import android.content.Context
import android.content.Intent
import android.database.sqlite.SQLiteException
import android.graphics.Color
import android.graphics.drawable.GradientDrawable
import android.graphics.drawable.LayerDrawable
import android.graphics.drawable.RippleDrawable
import android.inputmethodservice.InputMethodService
import android.os.Build
import android.text.InputType
import android.text.InputType.TYPE_CLASS_DATETIME
import android.text.InputType.TYPE_CLASS_NUMBER
import android.text.InputType.TYPE_CLASS_PHONE
import android.text.InputType.TYPE_MASK_CLASS
import android.util.Log
import android.view.KeyEvent
import android.view.View
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.EditorInfo.IME_ACTION_NONE
import android.view.inputmethod.EditorInfo.IME_FLAG_NO_ENTER_ACTION
import android.view.inputmethod.EditorInfo.IME_MASK_ACTION
import android.view.inputmethod.ExtractedTextRequest
import android.view.inputmethod.InputConnection
import android.widget.Button
import androidx.core.content.ContextCompat
import androidx.core.content.edit
import androidx.core.graphics.ColorUtils
import androidx.core.graphics.toColorInt
import androidx.core.view.ViewCompat
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import be.scri.R
import be.scri.activities.MainActivity
import be.scri.databinding.InputMethodViewBinding
import be.scri.helpers.AnnotationTextUtils.handleColorAndTextForNounType
import be.scri.helpers.AnnotationTextUtils.handleTextForCaseAnnotation
import be.scri.helpers.AutocompletionHandler
import be.scri.helpers.BackspaceHandler
import be.scri.helpers.DatabaseManagers
import be.scri.helpers.EmojiUtils.insertEmoji
import be.scri.helpers.KeyboardBase
import be.scri.helpers.LanguageMappingConstants.getLanguageAlias
import be.scri.helpers.NativeSuggestionEngine
import be.scri.helpers.PreferencesHelper
import be.scri.helpers.PreferencesHelper.getHoldKeyStyle
import be.scri.helpers.PreferencesHelper.getIsDarkModeOrNot
import be.scri.helpers.PreferencesHelper.getIsEmojiSuggestionsEnabled
import be.scri.helpers.PreferencesHelper.getIsSoundEnabled
import be.scri.helpers.PreferencesHelper.getIsVibrateEnabled
import be.scri.helpers.PreferencesHelper.isShowPopupOnKeypressEnabled
import be.scri.helpers.SHIFT_OFF
import be.scri.helpers.SHIFT_ON_ONE_CHAR
import be.scri.helpers.SHIFT_ON_PERMANENT
import be.scri.helpers.SuggestionHandler
import be.scri.helpers.data.AutocompletionDataManager
import be.scri.helpers.english.ENInterfaceVariables.ALREADY_PLURAL_MSG
import be.scri.helpers.ui.KeyboardUIManager
import be.scri.models.ScribeState
import be.scri.views.KeyboardView
import java.util.Locale
private const val DATA_SIZE_2 = 2
private const val DATA_CONSTANT_3 = 3
@Suppress("TooManyFunctions", "LargeClass")
abstract class GeneralKeyboardIME(
override var language: String,
) : InputMethodService(),
KeyboardView.OnKeyboardActionListener,
KeyboardUIManager.KeyboardUIListener,
KeyboardBase.KeyboardContextProvider {
// Abstract members required by subclasses (like EnglishKeyboardIME)
abstract override fun getKeyboardLayoutXML(): Int
abstract override val keyboardLetters: Int
abstract val keyboardSymbols: Int
abstract val keyboardSymbolShift: Int
open var keyboard: KeyboardBase? = null
var keyboardView: KeyboardView? = null
// UI Manager instance.
lateinit var uiManager: KeyboardUIManager
abstract var lastShiftPressTS: Long
abstract override var keyboardMode: Int
abstract var inputTypeClass: Int
abstract var enterKeyType: Int
abstract var switchToLetters: Boolean
/**
* Property used by EnglishKeyboardIME override.
* We define a custom getter here for the base logic, but subclasses can override the field.
*/
open var hasTextBeforeCursor: Boolean = false
get() {
val ic = currentInputConnection ?: return false
val text = ic.getTextBeforeCursor(Int.MAX_VALUE, 0)?.trim() ?: ""
return text.isNotEmpty() && text.lastOrNull() != '.'
}
set(value) {
field = value
}
// Delegate backspace handling to a separate class.
private val backspaceHandler = BackspaceHandler(this)
// Bridge for BackspaceHandler to access binding through UI Manager.
internal val binding: InputMethodViewBinding
get() = uiManager.binding
private enum class SwipeTutorialState {
NOT_ACTIVE,
SWIPE_LEFT_STEP,
SWIPE_RIGHT_STEP,
COMPLETED,
}
private var swipeTutorialState = SwipeTutorialState.NOT_ACTIVE
// MARK: State Variables
internal var isSingularAndPlural: Boolean = false
private var subsequentAreaRequired: Boolean = false
private var subsequentData: MutableList<List<String>> = mutableListOf()
private val shiftPermToggleSpeed: Int = DEFAULT_SHIFT_PERM_TOGGLE_SPEED
private lateinit var dbManagers: DatabaseManagers
private lateinit var nativeSuggestionEngine: NativeSuggestionEngine
internal lateinit var suggestionHandler: SuggestionHandler
internal lateinit var autocompletionHandler: AutocompletionHandler
private lateinit var autocompletionManager: AutocompletionDataManager
private var dataContract: DataContract? = null
var emojiKeywords: HashMap<String, MutableList<String>>? = null
private var conjugateOutput: MutableMap<String, MutableMap<String, Collection<String>>>? = null
private var conjugateLabels: Set<String> = emptySet()
private var emojiMaxKeywordLength: Int = 0
internal lateinit var nounKeywords: HashMap<String, List<String>>
internal lateinit var suggestionWords: HashMap<String, List<String>>
var pluralWords: Set<String>? = null
internal lateinit var caseAnnotation: HashMap<String, MutableList<String>>
var emojiAutoSuggestionEnabled: Boolean = false
var lastWord: String? = null
var autoSuggestEmojis: MutableList<String>? = null
var caseAnnotationSuggestion: MutableList<String>? = null
var nounTypeSuggestion: List<String>? = null
var wordSuggestions: List<String>? = null
var checkIfPluralWord: Boolean = false
private var currentEnterKeyType: Int? = null
private var isNumericKeyboardActive: Boolean = false
internal var currentState: ScribeState = ScribeState.IDLE
internal var invalidCommandSource: ScribeState = ScribeState.IDLE
// Properties used by BackspaceHandler, delegated to UI Manager.
internal var currentCommandBarHint: String
get() = uiManager.currentCommandBarHint
set(value) {
uiManager.currentCommandBarHint = value
}
internal var commandBarHintColor: Int
get() = uiManager.commandBarHintColor
set(value) {
uiManager.commandBarHintColor = value
}
// MARK: Conjugation State
private var currentVerbForConjugation: String? = null
private var selectedConjugationSubCategory: String? = null
internal companion object {
const val DEFAULT_SHIFT_PERM_TOGGLE_SPEED = 500
const val TEXT_LENGTH = 20
const val NOUN_TYPE_SIZE = 20f
const val SUGGESTION_SIZE = 15f
const val DARK_THEME = "#aeb3be"
const val LIGHT_THEME = "#4b4b4b"
internal const val MAX_TEXT_LENGTH = 1000
const val COMMIT_TEXT_CURSOR_POSITION = 1
internal const val CUSTOM_CURSOR = "│" // special tall cursor character
internal fun shouldUseNumericKeyboard(inputType: Int): Boolean =
when (inputType and TYPE_MASK_CLASS) {
TYPE_CLASS_NUMBER, TYPE_CLASS_DATETIME, TYPE_CLASS_PHONE -> true
else -> false
}
internal fun getKeyboardLayoutXMLForInputType(
inputType: Int,
letterKeyboardLayoutXML: Int,
): Int =
if (shouldUseNumericKeyboard(inputType)) {
R.xml.keys_numeric
} else {
letterKeyboardLayoutXML
}
}
// MARK: Lifecycle Methods
/**
* Called when the service is first created. Initializes database and suggestion handlers.
*/
override fun onCreate() {
super.onCreate()
dbManagers = DatabaseManagers(this)
nativeSuggestionEngine = NativeSuggestionEngine(this)
suggestionHandler = SuggestionHandler(this)
autocompletionManager = dbManagers.autocompletionManager
autocompletionHandler = AutocompletionHandler(this)
}
override fun onDestroy() {
if (this::nativeSuggestionEngine.isInitialized) {
nativeSuggestionEngine.close()
}
super.onDestroy()
}
/**
* Creates the main view for the input method, inflating it from XML and setting up the keyboard.
*
* @return The root View of the input method.
*/
override fun onCreateInputView(): View {
// Initialize UI manager.
val viewBinding = InputMethodViewBinding.inflate(layoutInflater)
uiManager = KeyboardUIManager(viewBinding, this, this)
keyboardView = uiManager.keyboardView
// Initial keyboard setup.
keyboard = KeyboardBase(this, getKeyboardLayoutXML(), enterKeyType)
keyboardView?.apply {
setVibrate = getIsVibrateEnabled(applicationContext, language)
setSound = getIsSoundEnabled(applicationContext, language)
setHoldForAltCharacters = getHoldKeyStyle(applicationContext, language)
setKeyboard(this@GeneralKeyboardIME.keyboard!!)
mOnKeyboardActionListener = this@GeneralKeyboardIME
}
currentState = ScribeState.IDLE
saveConjugateModeType("none")
refreshUI()
return viewBinding.root
}
/**
* Always show the input view. Required for API 36 onwards as edge-to-edge
* enforcement can cause the keyboard to not display if this returns false.
*/
override fun onEvaluateInputViewShown(): Boolean {
super.onEvaluateInputViewShown()
return true
}
/**
* Disable fullscreen mode to ensure the keyboard displays correctly on API 36 onwards.
* Fullscreen mode can interfere with edge-to-edge layouts.
*/
override fun onEvaluateFullscreenMode(): Boolean = false
/**
* Compute the insets for the keyboard view. This is essential for API 36+
* where the system needs to know the exact size of the keyboard to properly
* handle edge-to-edge display and window insets.
*/
override fun onComputeInsets(outInsets: Insets) {
super.onComputeInsets(outInsets)
// Access root view via UI manager if initialized.
if (this::uiManager.isInitialized) {
val inputView = uiManager.binding.root
if (inputView.visibility == View.VISIBLE && inputView.height > 0) {
val location = IntArray(2)
inputView.getLocationInWindow(location)
outInsets.visibleTopInsets = location[1]
outInsets.contentTopInsets = location[1]
outInsets.touchableInsets = Insets.TOUCHABLE_INSETS_VISIBLE
}
}
}
override fun onWindowShown() {
super.onWindowShown()
applyNavBarColor()
keyboardView?.setPreview = isShowPopupOnKeypressEnabled(applicationContext, language)
keyboardView?.setVibrate = getIsVibrateEnabled(applicationContext, language)
keyboardView?.setSound = getIsSoundEnabled(applicationContext, language)
keyboardView?.setHoldForAltCharacters = getHoldKeyStyle(applicationContext, language)
}
/**
* Called when the IME is starting to interact with a new input field.
* It initializes the keyboard based on the input type and loads all language-specific data.
*
* @param attribute The editor information for the new input field.
* @param restarting true if we are restarting the input with the same editor.
*/
override fun onStartInput(
attribute: EditorInfo?,
restarting: Boolean,
) {
super.onStartInput(attribute, restarting)
backspaceHandler.clearUndoStack()
inputTypeClass = attribute!!.inputType and TYPE_MASK_CLASS
enterKeyType = attribute.imeOptions and (IME_MASK_ACTION or IME_FLAG_NO_ENTER_ACTION)
currentEnterKeyType = enterKeyType
// This setter triggers the logic in the property override if not shadowed.
hasTextBeforeCursor = currentInputConnection?.getTextBeforeCursor(1, 0)?.isNotEmpty() == true
isNumericKeyboardActive = shouldUseNumericKeyboard(attribute.inputType)
keyboardMode = if (isNumericKeyboardActive) keyboardSymbols else keyboardLetters
val keyboardXml = getKeyboardLayoutXMLForInputType(attribute.inputType, getKeyboardLayoutXML())
loadLanguageData()
keyboard = KeyboardBase(this, keyboardXml, enterKeyType)
keyboardView?.setKeyboard(keyboard!!)
if (this::uiManager.isInitialized && keyboardXml == R.xml.keys_symbols) {
uiManager.setupCurrencySymbol(language)
}
}
/**
* Called when the input view is starting. It sets up the UI theme, emoji settings,
* and initial keyboard state.
*
* @param editorInfo The editor information for the input field.
* @param restarting true if we are restarting the input with the same editor.
*/
override fun onStartInputView(
editorInfo: EditorInfo?,
restarting: Boolean,
) {
super.onStartInputView(editorInfo, restarting)
emojiAutoSuggestionEnabled = getIsEmojiSuggestionsEnabled(applicationContext, language)
autoSuggestEmojis = null
suggestionHandler.clearAllSuggestionsAndHideButtonUI()
moveToIdleState()
val languageAlias = getLanguageAlias(language)
val dbFile = applicationContext.getDatabasePath("${languageAlias}LanguageData.sqlite")
val hasData = dbFile.exists()
val banner = binding.root.findViewById<Button>(R.id.empty_state_banner)
banner.visibility =
if (hasData) View.GONE else View.VISIBLE
binding.commandOptionsBar.visibility =
if (hasData && !isNumericKeyboardActive) View.VISIBLE else View.GONE
val isDarkMode = getIsDarkModeOrNot(applicationContext)
val bannerColor = if (isDarkMode) R.color.dark_tutorial_button_color else R.color.light_tutorial_button_color
val bannerTextColor = if (isDarkMode) R.color.dark_button_outline_color else R.color.light_text_color
banner.setTextColor(ContextCompat.getColor(applicationContext, bannerTextColor))
banner.post {
val iconColor = ContextCompat.getColor(applicationContext, bannerTextColor)
banner.compoundDrawables.forEach { drawable ->
drawable?.setTint(iconColor)
}
}
val border = GradientDrawable()
border.cornerRadius = 12f * resources.displayMetrics.density
border.setColor(ContextCompat.getColor(applicationContext, bannerColor))
if (isDarkMode) {
border.setStroke((2f * resources.displayMetrics.density).toInt(), ContextCompat.getColor(applicationContext, bannerTextColor))
}
val rippleColor =
ColorUtils.setAlphaComponent(
ContextCompat.getColor(applicationContext, bannerTextColor),
51,
)
val ripple =
RippleDrawable(
android.content.res.ColorStateList
.valueOf(rippleColor),
border,
null,
)
banner.background = ripple
banner.setOnClickListener {
val intent =
Intent(applicationContext, MainActivity::class.java)
.apply {
flags = Intent.FLAG_ACTIVITY_NEW_TASK
}
startActivity(intent)
}
applyNavBarColor()
// Set initial shift state for empty text fields.
if (keyboardMode == keyboardLetters) {
val textBefore = currentInputConnection?.getTextBeforeCursor(1, 0)?.toString().orEmpty()
if (textBefore.isEmpty()) {
keyboardView?.mKeyboard?.mShiftState = SHIFT_ON_ONE_CHAR
}
keyboardView?.invalidateAllKeys()
}
// Show swipe delete & undo gesture tutorial overlay if not already shown
initSwipeTutorial()
}
private fun initSwipeTutorial() {
val sharedPref = applicationContext.getSharedPreferences("app_preferences", MODE_PRIVATE)
val tutorialShown = sharedPref.getBoolean("swipe_tutorial_interactive_shown", false)
if (!tutorialShown) {
val ic = currentInputConnection
if (ic != null) {
ic.commitText("Scribe ", 1)
}
binding.swipeTutorialOverlay.visibility = View.VISIBLE
binding.swipeTutorialClose.setOnClickListener {
dismissSwipeTutorial()
}
setSwipeTutorialState(SwipeTutorialState.SWIPE_LEFT_STEP)
} else {
binding.swipeTutorialOverlay.visibility = View.GONE
swipeTutorialState = SwipeTutorialState.NOT_ACTIVE
}
}
private fun setSwipeTutorialState(state: SwipeTutorialState) {
swipeTutorialState = state
when (state) {
SwipeTutorialState.SWIPE_LEFT_STEP -> {
binding.swipeTutorialOverlay.visibility = View.VISIBLE
binding.swipeTutorialProgress.text = "Step 1 of 2"
binding.swipeTutorialIcon.setImageResource(R.drawable.ic_swipe_left)
binding.swipeTutorialTitle.text = "Swipe Left to Delete"
binding.swipeTutorialDesc.text = "Swipe left anywhere on the keyboard to delete the last word."
binding.swipeTutorialStatus.text = "Practice: Swipe left on the keyboard below to delete 'Scribe'!"
binding.swipeTutorialStatus.setTextColor(ContextCompat.getColor(applicationContext, R.color.theme_scribe_blue))
binding.swipeTutorialClose.text = "Skip"
}
SwipeTutorialState.SWIPE_RIGHT_STEP -> {
binding.swipeTutorialOverlay.visibility = View.VISIBLE
binding.swipeTutorialProgress.text = "Step 2 of 2"
binding.swipeTutorialIcon.setImageResource(R.drawable.ic_swipe_right)
binding.swipeTutorialTitle.text = "Swipe Right to Restore"
binding.swipeTutorialDesc.text = "Swipe right anywhere on the keyboard to restore/undo deletion."
binding.swipeTutorialStatus.text = "Practice: Swipe right now to restore the word!"
binding.swipeTutorialStatus.setTextColor(ContextCompat.getColor(applicationContext, R.color.theme_scribe_blue))
binding.swipeTutorialClose.text = "Skip"
}
SwipeTutorialState.COMPLETED -> {
binding.swipeTutorialOverlay.visibility = View.VISIBLE
binding.swipeTutorialProgress.text = "Tutorial Completed!"
binding.swipeTutorialIcon.setImageResource(R.drawable.ic_swipe_success)
binding.swipeTutorialTitle.text = "You're All Set!"
binding.swipeTutorialDesc.text = "You can swipe left to delete and swipe right to restore at any time."
binding.swipeTutorialStatus.text = "Success! Tap 'Got it!' to start typing."
binding.swipeTutorialStatus.setTextColor(android.graphics.Color.parseColor("#10B981"))
binding.swipeTutorialClose.text = "Got it!"
}
SwipeTutorialState.NOT_ACTIVE -> {
binding.swipeTutorialOverlay.visibility = View.GONE
}
}
}
private fun dismissSwipeTutorial() {
val sharedPref = applicationContext.getSharedPreferences("app_preferences", MODE_PRIVATE)
sharedPref.edit().putBoolean("swipe_tutorial_interactive_shown", true).apply()
setSwipeTutorialState(SwipeTutorialState.NOT_ACTIVE)
}
/**
* Called when the input view is finished. Resets the keyboard state to idle.
*
* @param finishingInput true if we are finishing for good,
* `false` if just switching to another app.
*/
override fun onFinishInputView(finishingInput: Boolean) {
super.onFinishInputView(finishingInput)
backspaceHandler.clearUndoStack()
moveToIdleState()
}
override fun onUpdateSelection(
oldSelStart: Int,
oldSelEnd: Int,
newSelStart: Int,
newSelEnd: Int,
candidatesStart: Int,
candidatesEnd: Int,
) {
super.onUpdateSelection(oldSelStart, oldSelEnd, newSelStart, newSelEnd, candidatesStart, candidatesEnd)
// If the selection/cursor changed manually (not from our programmatic swipe gestures within 500ms), clear the stack
val timeSinceLastSwipe = System.currentTimeMillis() - backspaceHandler.lastSwipeOperationTime
if (timeSinceLastSwipe > 500) {
backspaceHandler.clearUndoStack()
}
}
// MARK: OnKeyboardActionListener
/**
* Interface method called by KeyboardView.
* Delegates to the property 'hasTextBeforeCursor' which subclasses may override.
*/
override fun hasTextBeforeCursor(): Boolean = hasTextBeforeCursor
/**
* Handles the "period on double tap" feature. If enabled, it replaces the two spaces with a period and a space.
*/
override fun commitPeriodAfterSpace() {
if (currentState == ScribeState.IDLE || currentState == ScribeState.SELECT_COMMAND) {
val isPeriodOnDoubleTapEnabled = PreferencesHelper.getEnablePeriodOnSpaceBarDoubleTap(this, language)
if (isPeriodOnDoubleTapEnabled) {
currentInputConnection?.apply {
deleteSurroundingText(1, 0)
commitText(". ", 1)
}
} else {
currentInputConnection?.apply {
deleteSurroundingText(1, 0)
commitText(" ", 1)
}
}
}
}
/**
* Called when a key is pressed down. Triggers haptic feedback if enabled.
*
* @param primaryCode The integer code of the key that was pressed.
*/
override fun onPress(primaryCode: Int) {
if (primaryCode != 0) keyboardView?.vibrateIfNeeded()
if (primaryCode != 0) keyboardView?.soundIfNeeded()
}
/**
* Called when a key is released. Handles the logic
* to switch back to the letter keyboard
* after typing a character from the symbol keyboard.
*/
override fun onActionUp() {
if (switchToLetters) {
keyboardMode = keyboardLetters
keyboard = KeyboardBase(this, getKeyboardLayoutXML(), enterKeyType)
val editorInfo = currentInputEditorInfo
if (editorInfo != null && editorInfo.inputType != InputType.TYPE_NULL && keyboard?.mShiftState != SHIFT_ON_PERMANENT) {
if (currentInputConnection.getCursorCapsMode(editorInfo.inputType) != 0) {
keyboard?.setShifted(SHIFT_ON_ONE_CHAR)
}
}
keyboardView!!.setKeyboard(keyboard!!)
switchToLetters = false
}
}
override fun moveCursorLeft() = moveCursor(false)
override fun moveCursorRight() = moveCursor(true)
override fun onText(text: String) {
backspaceHandler.clearUndoStack()
currentInputConnection?.commitText(text, 0)
}
override fun onSwipeLeft() {
if (swipeTutorialState == SwipeTutorialState.SWIPE_LEFT_STEP) {
backspaceHandler.performSwipeDelete()
setSwipeTutorialState(SwipeTutorialState.SWIPE_RIGHT_STEP)
} else if (swipeTutorialState == SwipeTutorialState.NOT_ACTIVE) {
backspaceHandler.performSwipeDelete()
}
}
override fun onSwipeRight() {
if (swipeTutorialState == SwipeTutorialState.SWIPE_RIGHT_STEP) {
backspaceHandler.performSwipeRestore()
setSwipeTutorialState(SwipeTutorialState.COMPLETED)
} else if (swipeTutorialState == SwipeTutorialState.NOT_ACTIVE) {
backspaceHandler.performSwipeRestore()
}
}
/**
* Handles key input from the keyboard. Delegates to specific handlers based on the key code.
*/
override fun onKey(code: Int) {
if (code != KeyboardBase.KEYCODE_DELETE) {
backspaceHandler.clearUndoStack()
}
val inputConnection = currentInputConnection
if (inputConnection != null) {
when (code) {
KeyboardBase.KEYCODE_DELETE -> handleDelete()
KeyboardBase.KEYCODE_SHIFT -> {
if (keyboardMode == keyboardLetters) {
val shiftState = keyboardView?.mKeyboard?.mShiftState ?: SHIFT_OFF
when {
shiftState == SHIFT_ON_PERMANENT -> keyboardView?.setShifted(SHIFT_OFF)
System.currentTimeMillis() - lastShiftPressTS < shiftPermToggleSpeed -> keyboardView?.setShifted(SHIFT_ON_PERMANENT)
shiftState == SHIFT_ON_ONE_CHAR -> keyboardView?.setShifted(SHIFT_OFF)
shiftState == SHIFT_OFF -> keyboardView?.setShifted(SHIFT_ON_ONE_CHAR)
}
lastShiftPressTS = System.currentTimeMillis()
} else {
handleModeChange(keyboardMode, keyboardView, this)
}
}
KeyboardBase.KEYCODE_ENTER -> handleKeycodeEnter()
KeyboardBase.KEYCODE_MODE_CHANGE -> handleModeChange(keyboardMode, keyboardView, this)
else -> {
if (KeyboardBase.SCRIBE_VIEW_KEYS.contains(code)) {
val keyLabel = keyboardView?.getKeyLabel(code)
if (!keyLabel.isNullOrEmpty()) {
commitText("$keyLabel ")
}
} else {
val commandBarState = currentState != ScribeState.IDLE && currentState != ScribeState.SELECT_COMMAND
handleElseCondition(code, keyboardMode, commandBarState)
}
}
}
}
}
// MARK: Helper Methods
protected fun isPeriodAndCommaEnabled(): Boolean {
val isPreferenceEnabled = PreferencesHelper.getEnablePeriodAndCommaABC(this, language)
val isInSearchBar = isSearchBar()
return isPreferenceEnabled || isInSearchBar
}
/**
* This function is updated to reliably detect search bars in various apps,
* including browsers like Chrome and Firefox, not just fields with IME_ACTION_SEARCH.
* The logic is combined into a single return statement to satisfy the `detekt` ReturnCount rule.
* It checks multiple signals:
* 1. The explicit IME action for search.
* 2. The input type variation for URIs (common in address bars).
* 3. The hint text for keywords like "search" or "address".
*
* @return true if the current input field is likely a search or address bar, false otherwise.
*/
override fun isSearchBar(): Boolean {
val editorInfo = currentInputEditorInfo
val isActionSearch = (enterKeyType == EditorInfo.IME_ACTION_SEARCH)
val isUriType = editorInfo?.let { (it.inputType and InputType.TYPE_TEXT_VARIATION_URI) != 0 } == true
val hasSearchHint =
editorInfo?.hintText?.toString()?.lowercase(Locale.ROOT)?.let {
it.contains("search") || it.contains("address")
} == true
return isActionSearch || isUriType || hasSearchHint
}
private fun loadLanguageData() {
val languageAlias = getLanguageAlias(language)
dataContract = dbManagers.getLanguageContract(languageAlias)
emojiKeywords = dbManagers.emojiManager.getEmojiKeywords(languageAlias)
emojiMaxKeywordLength = dbManagers.emojiManager.maxKeywordLength
pluralWords =
dbManagers.pluralManager
.getAllPluralForms(languageAlias, dataContract)
?.map { it.lowercase() }
?.toSet()
nounKeywords = dbManagers.genderManager.findGenderOfWord(languageAlias, dataContract)
suggestionWords = dbManagers.suggestionManager.getSuggestions(languageAlias)
val numbersColumns =
dataContract?.numbers?.let { map ->
(map.keys + map.values).distinct()
} ?: emptyList()
autocompletionManager.loadWords(languageAlias, numbersColumns)
caseAnnotation = dbManagers.prepositionManager.getCaseAnnotations(languageAlias)
val tempConjugateOutput = dbManagers.conjugateDataManager.getTheConjugateLabels(languageAlias, dataContract, "describe")
conjugateOutput = if (tempConjugateOutput?.isEmpty() == true) null else tempConjugateOutput
conjugateLabels = dbManagers.conjugateDataManager.extractConjugateHeadings(dataContract, "coacha")
}
private fun isLightColor(color: Int): Boolean {
val darkness = 1 - (0.299 * Color.red(color) + 0.587 * Color.green(color) + 0.114 * Color.blue(color)) / 255
return darkness < 0.5
}
private fun applyNavBarColor() {
val window = window?.window ?: return
val isDarkMode = getIsDarkModeOrNot(applicationContext)
val colorRes = if (isDarkMode) R.color.dark_keyboard_bg_color else R.color.light_keyboard_bg_color
val color = ContextCompat.getColor(this, colorRes)
if (Build.VERSION.SDK_INT >= 35) {
WindowCompat.setDecorFitsSystemWindows(window, false)
} else {
window.navigationBarColor = Color.TRANSPARENT
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
window.isNavigationBarContrastEnforced = false
}
window.decorView.setBackgroundColor(color)
val insetsController = WindowCompat.getInsetsController(window, window.decorView)
insetsController.isAppearanceLightNavigationBars = isLightColor(color)
if (this::uiManager.isInitialized) {
uiManager.binding.root.setBackgroundColor(color)
ViewCompat.setOnApplyWindowInsetsListener(uiManager.binding.root) { view, insets ->
val insetTypes = WindowInsetsCompat.Type.systemBars() or WindowInsetsCompat.Type.displayCutout()
val navBarHeight = insets.getInsets(insetTypes).bottom
view.setPadding(0, 0, 0, navBarHeight)
insets
}
uiManager.binding.root.post {
ViewCompat.requestApplyInsets(uiManager.binding.root)
}
}
}
/**
* Saves the type of conjugation layout being used (e.g., "2x2", "3x2") to shared preferences.
*
* @param language The current keyboard language.
* @param isSubsequentArea true if this is for a secondary view.
*/
internal fun saveConjugateModeType(
language: String,
isSubsequentArea: Boolean = false,
) {
val sharedPref = applicationContext.getSharedPreferences("keyboard_preferences", MODE_PRIVATE)
val mode =
if (!isSubsequentArea) {
when (language) {
"English", "Russian", "Swedish" -> "2x2"
"German", "French", "Italian", "Portuguese", "Spanish" -> "3x2"
else -> "none"
}
} else {
"none"
}
sharedPref.edit { putString("conjugate_mode_type", mode) }
}
// MARK: UI Update Delegation
/**
* The main dispatcher for updating the entire keyboard UI. It calls the appropriate setup function
* based on the current [ScribeState].
*/
internal fun updateUI() = refreshUI()
private fun refreshUI() {
if (!this::uiManager.isInitialized) return
uiManager.updateUI(
currentState = currentState,
language = language,
emojiAutoSuggestionEnabled = emojiAutoSuggestionEnabled,
autoSuggestEmojis = autoSuggestEmojis,
conjugateOutput = conjugateOutput,
conjugateLabels = conjugateLabels,
selectedConjugationSubCategory = selectedConjugationSubCategory,
currentVerbForConjugation = currentVerbForConjugation,
invalidCommandSource = invalidCommandSource,
)
}
/**
* Transitions the keyboard to the `IDLE` state and updates the UI.
*/
internal fun moveToIdleState() {
clearSuggestionData()
currentState = ScribeState.IDLE
saveConjugateModeType("none")
currentVerbForConjugation = null
selectedConjugationSubCategory = null
if (this::uiManager.isInitialized) refreshUI()
}
/**
* Clears all cached suggestion data.
*/
private fun clearSuggestionData() {
autoSuggestEmojis = null
nounTypeSuggestion = null
caseAnnotationSuggestion = null
isSingularAndPlural = false
}
// MARK: KeyboardUIListener
override fun onScribeKeyOptionsClicked() {
if (currentState == ScribeState.IDLE) {
clearSuggestionData()
currentState = ScribeState.SELECT_COMMAND
saveConjugateModeType("none")
currentVerbForConjugation = null
} else {
moveToIdleState()
}
refreshUI()
}
override fun onScribeKeyToolbarClicked() {
moveToIdleState()
}
override fun onTranslateClicked() {
currentState = ScribeState.TRANSLATE
saveConjugateModeType("none")
refreshUI()
}
override fun onConjugateClicked() {
if (currentState != ScribeState.SELECT_VERB_CONJUNCTION) {
currentState = ScribeState.CONJUGATE
}
refreshUI()
}
override fun onPluralClicked() {
currentState = ScribeState.PLURAL
saveConjugateModeType("none")
if (language == "German") keyboard?.mShiftState = SHIFT_ON_ONE_CHAR
refreshUI()
}
override fun onCloseClicked() {
moveToIdleState()
}
override fun onEmojiSelected(emoji: String) {
if (emoji.isNotEmpty()) {
backspaceHandler.clearUndoStack()
insertEmoji(emoji, currentInputConnection, emojiKeywords, emojiMaxKeywordLength)
}
}
override fun onSuggestionClicked(suggestion: String) {
backspaceHandler.clearUndoStack()
currentInputConnection?.commitText("$suggestion ", 1)
moveToIdleState()
}
override fun getCurrentEnterKeyType(): Int = enterKeyType
override fun isNumericKeyboardActive(): Boolean = isNumericKeyboardActive
override fun getCurrentKeyboardLayoutXML(): Int =
when (keyboardMode) {
keyboardSymbols -> getPrimarySymbolKeyboardLayoutXML()
keyboardSymbolShift -> R.xml.keys_symbols_shift
else -> getKeyboardLayoutXML()
}
private fun getPrimarySymbolKeyboardLayoutXML(): Int =
if (isNumericKeyboardActive) {
R.xml.keys_numeric
} else {
R.xml.keys_symbols
}
override fun onKeyboardActionListener(): KeyboardView.OnKeyboardActionListener = this
override fun processLinguisticSuggestions(word: String) {
suggestionHandler.processLinguisticSuggestions(word)
}
override fun commitText(text: String) {
backspaceHandler.clearUndoStack()
if (currentState == ScribeState.SELECT_VERB_CONJUNCTION) {
val label = text.trim()
val conjugateIndex = getValidatedConjugateIndex()
val title = conjugateOutput?.keys?.elementAtOrNull(conjugateIndex)
val languageOutput = title?.let { conjugateOutput!![it] }
val matchingEntry =
languageOutput?.entries?.find { (_, values) ->
if (values.size == 1) values.first() == label else values.joinToString(" / ") == label
}
if (matchingEntry != null) {
val (key, values) = matchingEntry
if (values.size > 1) {
selectedConjugationSubCategory = key
refreshUI()
return
}
}
}
currentInputConnection?.commitText(text, 1)
suggestionHandler.processLinguisticSuggestions(text.trim())
if (currentState == ScribeState.SELECT_VERB_CONJUNCTION) {
selectedConjugationSubCategory = null
moveToIdleState()
}
}
// MARK: Input Logic
/**
* Handles the logic for the Enter key press. This can either perform an editor action,
* commit a newline, or execute a Scribe command depending on the current state.
*/
fun handleKeycodeEnter() {
val inputConnection = currentInputConnection ?: return
if (currentState == ScribeState.INVALID || currentState == ScribeState.ALREADY_PLURAL) {
moveToIdleState()
return
}
if (currentState == ScribeState.IDLE || currentState == ScribeState.SELECT_COMMAND) {
handleDefaultEnter(inputConnection)
return
}
val rawInput = uiManager.getCommandBarTextWithoutCursor().trim().takeIf { it.isNotEmpty() }
if (rawInput == null) {
moveToIdleState()
} else {
when (currentState) {
ScribeState.PLURAL, ScribeState.TRANSLATE -> handlePluralOrTranslateState(rawInput, inputConnection)
ScribeState.CONJUGATE -> handleConjugateState(rawInput)
else -> handleDefaultEnter(inputConnection)
}
}
}
/**
* Handles the Enter key press when in the plural or translate state.
*
* @param rawInput The text from the command bar.
* @param inputConnection The current input connection.
*/
private fun handlePluralOrTranslateState(
rawInput: String,
inputConnection: InputConnection,
) {
val isAllCaps = rawInput.isNotEmpty() && rawInput.all { !it.isLetter() || it.isUpperCase() }
val commandModeOutput =
when (currentState) {
ScribeState.PLURAL -> {
when (val pluralResult = getPluralRepresentation(rawInput)) {
ALREADY_PLURAL_MSG -> {
currentState = ScribeState.ALREADY_PLURAL
refreshUI()
return
}
null -> ""
else -> if (isAllCaps) pluralResult.uppercase() else pluralResult
}
}
ScribeState.TRANSLATE -> {
val translation = getTranslation(language, rawInput)
if (isAllCaps) translation.uppercase() else translation
}
else -> ""
}
if (commandModeOutput.isEmpty()) {
invalidCommandSource = currentState
currentState = ScribeState.INVALID
refreshUI()
} else {
applyCommandOutput(commandModeOutput, inputConnection)
}
}
/**
* Handles the Enter key press when in the `CONJUGATE` state. It fetches the
* conjugation data for the entered verb and transitions to the selection view.
*
* @param rawInput The verb entered in the command bar.